swift 5 autoresizingMask根本不起作用

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

我通过编程熟悉Autolayout,但我也想尝试通过编程自动调整大小。我创建了一个绿色框,并且希望水平居中,但顶部和底部的距离固定,但是无论我尝试使用autoresizingMask的任何组合如何,它都行不通。

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    view.autoresizesSubviews = true
    view.translatesAutoresizingMaskIntoConstraints = true

    let myView = UIView(frame: CGRect(x: 175, y: 100, width: 30, height: 30))
    myView.backgroundColor = .green
    view.addSubview(myView)
    myView.autoresizingMask = [.flexibleRightMargin, .flexibleLeftMargin]
}

[我在iphone SE2和iphone 11 Pro Max上尝试过,绿色块位于SE中央,但从不在Pro Max上,有人知道这是怎么回事吗?

ios swift autoresizingmask
1个回答
0
投票

自动调整大小是根据视图的框架和自动调整蒙版来维护视图。因此,如果要使该视图居中,则第一步是将其[

myView.center = CGPoint(x:view.bounds.midX, y:view.bounds.midY)
现在使所有四个边距都具有灵活性,并且视图将相对于任何屏幕尺寸保持在放置位置。    
© www.soinside.com 2019 - 2024. All rights reserved.