【问题标题】:autoresizingMask not working as expected for UITableView.tableHeaderView's subview对于 UITableView.tableHeaderView 的子视图,autoresizingMask 未按预期工作
【发布时间】:2020-12-13 18:37:20
【问题描述】:

我正在向我的 UITableView 添加一个标题视图,并希望向它添加一个具有一些边距的子视图。

class ViewController: UIViewController {
    
    private let tablewView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        tablewView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(tablewView)
        [
            tablewView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
            tablewView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
            tablewView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tablewView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ].forEach{ $0.isActive = true}

        let headerView = UIView(frame: CGRect(x: 0, y: 120, width: 200, height: 100))
        headerView.backgroundColor = .blue
        
        let subView = UIView(frame: CGRect(x: 10, y: 10, width: 180, height: 80))
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.backgroundColor = .yellow
        headerView.addSubview(subView)
        
        tablewView.tableHeaderView = headerView
    }
}

问题是当标题被调整大小时(当表格视图被布局时),右边距没有被保留。正如您在图像上看到的,缺少右边距:

如果我在没有 UITableView 的情况下使用相同的视图,则按预期保留边距。

这是一个 UIKit 错误吗?有什么解决方法吗?

我知道我可以从这里Is it possible to use AutoLayout with UITableView's tableHeaderView? 尝试 AutoLayout 解决方案,但它们看起来有点老套。毕竟autoresizingMask 应该可以工作。

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

    在 Cocoa 编程中和在喜剧中一样,时间就是一切。

    viewDidLayoutSubviews 的一次性实现中添加子视图,一切都会好起来的。子视图将正确显示,并且在调整表格视图大小时(例如由于界面的旋转)将继续工作。

    所以,剪掉这四行:

        let subView = UIView(frame: CGRect(x: 10, y: 10, width: 180, height: 80))
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.backgroundColor = .yellow
        headerView.addSubview(subView)
    

    相反:

    var didLayout = false
    override func viewDidLayoutSubviews() {
        guard !didLayout else { return }
        didLayout.toggle()
        if let h = tablewView.tableHeaderView {
            let subView = UIView(frame: h.bounds.insetBy(dx: 10, dy: 10))
            subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            subView.backgroundColor = .yellow
            h.addSubview(subView)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 2022-01-27
      • 2023-03-08
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2017-03-22
      相关资源
      最近更新 更多