ios - 重新加载部分时 tableview 标题 uiview 消失

标签 ios swift uitableview tableview

我想通过点击它的标题来创建一个可扩展的表格 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/

相关文章:

iOS:未调用 didSelectRowAtIndexPath

android - 在 Flutter 中从客户设备检索日志

arrays - 如何快速调用或访问结构计算变量?

ios - 如何从自定义 TableViewCell 访问 ViewController 的 navigationController

ios - 具有许多图像的 UITableView 内存使用率高

swift - 如何快速删除 UIMenuController 项?

ios - AVFoundation -AVCaptureSession 仅在进入后台并返回断点时停止并开始运行

ios - FirebaseHandle 上的编译错误

ios - 使用CMDeviceMotion获取绝对旋转?

swift - 将分数上传到 GameCenter,无法添加两个二进制操作数