使用自动布局和布局指南来构建您的 UI。例如,使用 SnapKit。
let topBar = UIView(frame:CGRect(x: 0,y: 0, width: width, height: 60))
topBar.snp.makeConstraints { make in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
make.leading.trailing.equalToSuperview()
}
更新
用原始api重写。
let topBar = UIView(frame:CGRect(x: 0,y: 0, width: 30, height: 60))
self.view.addSubview(topBar)
let top = NSLayoutConstraint.init(item: topBar, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: 0.0)
let leading = NSLayoutConstraint.init(item: topBar, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailing = NSLayoutConstraint.init(item: topBar, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let height = NSLayoutConstraint.init(item: topBar, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50.0)
topBar.addConstraints([top, leading, trailing, height])