【发布时间】:2020-01-20 17:23:49
【问题描述】:
我正在使用 Swift 5 和 Xcode 11 创建一个带有 3 个单独的视图控制器(2 个常规视图,1 个表视图)的选项卡式应用程序。在我的第三个视图(即带有表视图的视图)内部,以及我的内部UITableViewCells,有 1 个按钮,颜色为红色。我在我的两台测试设备上测试了我的程序,一台屏幕较大,另一台屏幕较小,iPhone 5s,以下是我得到的结果:
大屏 iPhone(iPhone 6 Plus): 一切正常,即使我选择了 UITableViewCell,里面的项目也不会消失
iPhone 5s: 如果我不选择 UITableViewCell,一切都会好起来的: 但是如果我选择了 UITableViewCell,里面的项目就会消失:
这是我的 uitableviewcontroller:
import UIKit
@objcMembers class CustomViewController: UITableViewController {
var tag = 0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
}
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
tag = tag + 1
let cell = tableView.dequeueReusableCell(withIdentifier: "themeCell", for: indexPath) as! ThemeCell
/////////
let cellButton = UIButton(frame: CGRect(x: 0, y: 5, width: 50, height: 30))
cellButton.translatesAutoresizingMaskIntoConstraints = false
cell.addSubview(cellButton)
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.red
cellButton.leadingAnchor.constraint(equalTo: cell.leadingAnchor, constant: 10).isActive = true
cellButton.topAnchor.constraint(equalTo: cell.topAnchor, constant: 5).isActive = true
cellButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
cellButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
cell.img.image = UIImage(named: SingletonViewController.themes[indexPath.row])
cell.accessoryView = cellButton
cellButton.backgroundColor = UIColor.red
cellButton.addTarget(self, action: #selector(CustomViewController.backBTN(sender:)), for: .touchUpInside)
cellButton.tag = tag
return cell
}
}
知道为什么会这样吗?
【问题讨论】:
-
也许不相关,但你为什么不断增加
tag?以及为什么按钮的backgroundColor设置了两次,而按钮分配给了accessoryView两次?。为什么还要添加按钮作为单元格的子视图?为什么每次重复使用细胞时还要多次?好的,如果numberOfRows保持为 1,则最后一个 why 无关紧要。 -
@vadian 1. 我正在使用标签来标记我制作的按钮(尚未使用它) 2. 我打算制作两个按钮,但还没完成 3/4 .我将重用单元格(但还没有,稍后会这样做)
-
而不是额外的属性使用索引路径的
row作为tag。使用您的方式,您将无法识别单元格。如果它用作附件视图,则不需要将按钮添加为子视图。无论如何,我都会在 Interface Builder 中设计按钮。 -
@vadian 感谢您的建议,这对我有帮助。
标签: ios swift xcode uitableview