在情节提要中:
在代码中,添加另一个视图。我在蓝色视图中放置新视图并将其居中
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 X上,问题的视图超出了范围
最佳答案
由于屏幕尺寸不同,因此请更换
let newView = UIView(frame: CGRect(x: 0, y: 0, width: 380, height: 100))
与
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)
])
要更正视图的访问框架,它应该位于
viewDidLayoutSubviews
而不是viewDidLoad
内关于ios - Xcode和Swift。宽度是自动计算的,但在iPhone Xr上一切正常,在iPhone X上看起来很差,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59646284/