我有一个已实现的自定义 View ,我正在尝试学习如何在不使用 Storyboard的情况下使用自动布局。
我的问题是我是否需要使用框架来初始化我的 View ,或者我是否可以只执行一个空的初始化然后使用自动布局让 View 自行确定宽度和高度?
在下面你会看到我尝试添加框架然后放置自动布局认为我必须先放置框架然后自动布局更改它。
let origin = CGPoint(x: 0.0, y: 0.0)
let size = CGSize(width: view.frame.width, height: 44.0)
let frame = CGRect(origin: origin, size: size)
customView = ExpandableHeadingView(frame: headingFrame)
customView.frame.size.height = 44.0
view.addSubview(customView)
view.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true
view.leftAnchor.constraint(equalTo: customView.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: customView.rightAnchor).isActive = true
view.heightAnchor.constraint(equalTo: customView.heightAnchor).isActive = true
最佳答案
你不应该设置框架。您只需要为自动布局设置足够的约束,以便能够为您设置它。
您遗漏的一件事可能是一个问题:
customView.translatesAutoresizingMaskIntoConstraints = false
如果您在代码中创建一个 View ,您通常需要手动设置它以便能够正确地使用自动布局。
关于ios - View 是否需要使用框架初始化,然后让自动布局更改它或只使用自动布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44293721/