Xcode 和 Swift。宽度是自动计算的,但在 iPhone Xr 上一切正常,在 iPhone X 上看起来很糟糕

Xcode and Swift. The width is calculated automatically, but on the iPhone Xr everything is fine and on the iPhone X it looks bad

在情节提要中:

在代码中,添加另一个视图。我在蓝色视图中放置新视图并将其居中

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 上看起来不错

关于iPhoneX问题观点超越

由于屏幕尺寸不同,所以替换

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

试试这个

override func viewDidLoad() {
    super.viewDidLoad()
    print(viewTest.frame.width)
    let newView = UIView(frame: CGRect(x: 10, y: 10, width: viewTest.frame.width-20, height: viewTest.frame.height-20))
    newView.backgroundColor = .red
    viewTest.addSubview(newView)

}

谢谢,只有这个对我有用:

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 中做什么 view.width对于iPhoneX和iPhoneXr是一样的,只是屏幕宽度不同