【问题标题】:addSubview not working after converting转换后 addSubview 不起作用
【发布时间】:2017-01-01 20:54:37
【问题描述】:

我将 xcode 从 7.3.1 升级到 8 并转换为 swift 2.2,除了故事板一团糟,除了以编程方式添加 UIView 外,一切正常。

这之前工作正常,现在什么都没有显示,也没有错误。有什么想法吗?

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //create view
    let vw = UIView()
    vw.backgroundColor = UIColor(red: 0.9137, green: 0.9176, blue: 0.9216, alpha: 1.0) /* #e9eaeb */

    //create label inside view
    let label: UILabel = UILabel()
    label.frame =  CGRectMake(0, 0, 200, 28)
    label.textAlignment = NSTextAlignment.Left
    label.textColor = UIColor.grayColor()
    label.font = label.font.fontWithSize(13)

    if !clearSearch {
        label.text = "  Recent Searches"
    } else {
        label.text = "  Search Results"
    }
    vw.addSubview(label)

    //create button inside view
    let button: UIButton = UIButton()
    button.frame = CGRectMake(self.view.frame.size.width - 45, 0, 40, 28)
    button.titleLabel?.font = UIFont.systemFontOfSize(13)
    button.setTitle("Clear", forState: UIControlState.Normal)
    button.addTarget(self, action: #selector(deleteSearches), forControlEvents: UIControlEvents.TouchUpInside)
    button.setTitleColor(UIColor(red: 0.3216, green: 0.7176, blue: 0.5333, alpha: 1.0), forState: UIControlState.Normal)
    vw.addSubview(button)

    return vw
}

感谢您的帮助。

【问题讨论】:

  • 这一切看起来都很好。您应该在 return 语句中验证 vw 是否非零(应该是),然后检查调用代码中发生了什么。我怀疑问题在那里。您还应该尝试使用 Debug->View Debugging->Capture View Hierarchy 工具来查看发生了什么。
  • 您好,感谢您的快速回复。是的,看起来那个功能块甚至不再被调用了,很奇怪,我没有改变任何东西。我也按照您的建议尝试了调试,但它也没有显示在那里。
  • 想通了,现在需要 heightForHeaderInSection。
  • 很高兴您找到了解决方案。

标签: ios uiview swift2 xcode8 addsubview


【解决方案1】:

现在看来这是必需的。

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 28
}

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多