如何以编程方式快速将子视图添加到自定义视图

时间:2019-08-06 13:15:46

标签: ios swift

我想在我的自定义视图中添加一个子视图(UIButton)。但是,当我在创建的函数中执行addSubview()时,即使我调用setNeedsLayout(),也不会添加UIButton。我在ViewController中调用addButton()

class PlayingField: UIView {

    var buttons: [UIButton] = []

    func addButton() {
        let button = UIButton()
        addSubview(button)
        buttons.append(button)
        setNeedsLayout()
        layoutIfNeeded()
    }

    override func layoutSubviews() {
        for i in buttons.indices {
            buttons[i].frame = CGRect(x: 50, y: 50, width: 100, height: 100)
            buttons[i].backgroundColor = UIColor.green
        }
    }
}

2 个答案:

答案 0 :(得分:0)

确定要绘制items.filter(item => item[0] && item[0].toLowerCase() === "a") 吗?您是否在此视图中看到其他组件?

因为如果有一个CustomView文件绑定到此文件,则可能需要加载笔尖。您可以在此处找到有关此操作的答案:Load UIView from nib

否则,您可能会遇到未调用xib的问题,这就是为什么根本不添加子视图的原因。

答案 1 :(得分:0)

使用您发布的原始代码,这是一个完整的示例:

class CustomView: UIView {
    var buttons: [UIButton] = []

    func addButton() {
        let button = UIButton(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
        buttons.append(button)
        setNeedsLayout()
    }

    override func layoutSubviews() {
        for i in buttons.indices {
            buttons[i].frame = bounds.offsetBy(dx: CGFloat(20), dy: CGFloat(20))
            buttons[i].backgroundColor = UIColor.black
            addSubview(buttons[i])
        }
    }
}

class CustomViewController: UIViewController {

    let cView: CustomView = {
        let v = CustomView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(cView)

        NSLayoutConstraint.activate([
            cView.widthAnchor.constraint(equalToConstant: 240),
            cView.heightAnchor.constraint(equalToConstant: 120),
            cView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            cView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            ])

        cView.addButton()
    }

}

结果-青色矩形是CustomView ...黑色矩形是按钮:

enter image description here

作为附带说明,这是可行的,但是使用layoutSubviews()添加元素并不是一个好主意。

相关问题