在情节提要中:in storyboard
在代码中,添加另一个视图。我将新视图放置在蓝色视图中并居中]
override func viewDidLoad() {
super.viewDidLoad()
print(viewTest.frame.width)
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 380, height: 100))
newView.backgroundColor = .red
let x = viewTest.frame.width / 2 - newView.frame.width / 2
let y = viewTest.frame.height / 2 - newView.frame.height / 2
newView.frame = CGRect(x: x, y: y, width: newView.frame.width, height: newView.frame.height)
viewTest.addSubview(newView)
}
在iPhone Xr上看起来不错iPhone Xr
关于iPhone X问题的观点超越了iPhone X
由于屏幕尺寸不同,请更换
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 380, height: 100))
with
let newView = UIView(frame: CGRect(x: 0, y: 0, width:view.frame.width - 40.0, height: 100))
最好]
newView.translatesAutoresizingMaskIntoConstraints = false
viewTest.addSubview(newView)
NSLayoutConstraint.activate([
newView.centerYAnchor.constraint(equalTo:viewTest.centerYAnchor),
newView.rightAnchor.constraint(equalTo:viewTest.rightAnchor,constant:-10),
newView.leftAnchor.constraint(equalTo: viewTest.leftAnchor,constant:10),
newView.heightAnchor.constraint(equalToConstant:100)
])