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

问题描述 投票:0回答:1

在情节提要中: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

ios swift iphone xcode height
1个回答
0
投票

由于屏幕尺寸不同,请更换

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)
    ])
© www.soinside.com 2019 - 2024. All rights reserved.