我想通过点击它的标题来创建一个可扩展的表格 View ,我有一个在 viewForHeaderInSection 中调用的 headerfooterview 类来实例化标题,在我尝试重新加载该部分之前它看起来很好,当该部分折叠时 subview 消失。
代码如下
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(CustomHeaderTableViewCell.self, forHeaderFooterViewReuseIdentifier: "header")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == selectedSection {
return 0
} else {
return data[section].count
}
}
func expandCollapse(sender: UIButton) {
self.selectedSection = sender.tag
tableView.reloadSections(NSIndexSet( index: sender.tag ), withRowAnimation: .None)
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header: CustomHeaderTableViewCell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! CustomHeaderTableViewCell
let button = UIButton(type: UIButtonType.System) as UIButton
button.frame = header.bounds
button.backgroundColor = UIColor.greenColor()
button.setTitle("Test Button", forState: UIControlState.Normal)
button.addTarget(self, action: #selector(MainWitness.expandCollapse), forControlEvents: UIControlEvents.TouchUpInside)
button.tag = section
header.addSubview(button)
header.textLabel!.text = "TRENDS"
return header
}
最佳答案
header 的 subview ,在这种情况下,您的按钮消失的原因是headerView 的高度在方法func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
中不正确。
headerView 的高度仍为零(宽度也是如此),因此当您的代码执行 button.frame = header.bounds
时,高度将被设置为零,宽度也将被设置为零。所以它可能不会在屏幕上看到。
为了解决这个问题,你可以用一些固定的矩形设置按钮的框架,比如CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 30)
。 .
关于ios - 重新加载部分时 tableview 标题 uiview 消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36564149/