如何在 swift 中获取超级视图的框架?

How can I get frame of superview's frame in swift?

我想创建多个按钮并将其放置在 uiview 中并适合 uiview。(如图)

我需要获取 uiview 框架来根据需要进行计算和划分,根据设备大小设置按钮的宽度和高度。

        for row in 0 ..< 4 {
        for col in 0..<3 {
            let numberButton = UIButton()
            numberButton.frame = CGRect(x: Int(buttonView.frame.width / 3 - 20) * col, y: row * (320 / 4), width: Int(buttonView.frame.width) / 3, height: Int(buttonView.frame.height) / 4)
            numberButton.setTitle("button", for: .normal)
            numberButton.titleLabel?.font = numberButton.titleLabel?.font.withSize(30)
            numberButton.setTitleColor(UIColor.black)

            buttonView.addSubview(numberButton)
        }

    }

我试过上面的代码,但是 buttonView.frame.width returns 没有。

如何计算此视图的框架?

您可以使用 UIStackViews 来实现此网格布局。这样,您就不必计算每个按钮的帧数。无论如何,这样做是不好的做法。您应该改为使用 AutoLayout 约束来布局您的视图。这里有一个 tutorial 可以帮助您入门。

无论如何,下面是使用 UIStackViews 创建按钮网格的方法:

// here I hardcoded the frame of the button view, but in reality you should add
// AutoLayout constraints to it to specify its frame
let buttonView = UIStackView(frame: CGRect(x: 0, y: 0, width: 600, height: 320))
buttonView.alignment = .fill
buttonView.axis = .vertical
buttonView.distribution = .fillEqually
buttonView.spacing = 20 // this is the spacing between each row of buttons
for _ in 0..<4 {
    var buttons = [UIButton]()
    for _ in 0..<3 {
        let numberButton = UIButton(type: .system)
        numberButton.setTitle("button", for: .normal)
        numberButton.titleLabel?.font = numberButton.titleLabel?.font.withSize(30)
        numberButton.setTitleColor(UIColor.black, for: .normal)
        // customise your button more if you want...
        buttons.append(numberButton)
    }
    let horizontalStackView = UIStackView(arrangedSubviews: buttons)
    horizontalStackView.alignment = .fill
    horizontalStackView.axis = .horizontal
    horizontalStackView.distribution = .fillEqually
    horizontalStackView.spacing = 20 // this is the spacing between each column of buttons
    buttonView.addArrangedSubview(horizontalStackView)
}

playground 快速查看结果: