如何分隔创建的数组中的按钮?

时间:2017-06-27 15:30:49

标签: ios swift3

我想制作一个弹出式菜单,它是一个包含一系列按钮的UIView,这些按钮应该并排存在。相反,尽管我动态地更改了center.x,但它们都堆叠在一起。这是我的代码段:

func createPopUpView(number: Int) -> UIView{
    let popUpView: UIView = UIView()
    var buttons: [UIButton] = [UIButton]()
    let button: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height:42))
    button.backgroundColor = UIColor.black
    button.layer.cornerRadius = 5
    for i in 0..<number {
        buttons.append(button)
        buttons[i].setTitle(String(i), for: .normal)
        buttons[i].center.x += 32
        popUpView.addSubview(buttons[i])
    }       
    return popUpView        
}

谢谢。

1 个答案:

答案 0 :(得分:0)

每次循环都需要创建一个新按钮。另外,在创建popUpView时需要提供一个框架......

试试这样:

func createPopUpView(number: Int) -> UIView{
    let popUpView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: number * 32, height: 42))
    for i in 0..<number {
        let button: UIButton = UIButton(frame: CGRect(x: i * 32, y: 0, width: 32, height:42))
        button.backgroundColor = UIColor.black
        button.layer.cornerRadius = 5
        button.setTitle(String(i), for: .normal)
        popUpView.addSubview(button)
    }
    return popUpView
}