如何在swift中创建动态的堆栈视图?

时间:2016-02-17 13:13:04

标签: ios xcode swift uistackview

嗨我开发了一个用于四个堆栈视图的程序,在同一个视图中添加另一个堆栈我需要另一个子视图,是否还有其他方法可以使用for循环添加子视图,我是快速语言和学习的新手,请需要帮助

如何在for循环中保留所有堆栈视图,以便我可以添加n个堆栈视图

1 个答案:

答案 0 :(得分:1)

以下是使用UIStackViews构建键盘的代码片段...

func newPad() {
    keyPadWindow = UIView(frame: CGRect(x: 128, y: 224, width: 512, height: 356))
    keyPadWindow.backgroundColor  = UIColor.yellowColor()
    var keyCount = 0
    keyPadSV = UIStackView(frame: CGRect(x: 0, y: 0, width: 512, height: 356))
    keyPadSV!.axis = .Vertical
    keyPadSV!.spacing = 0.0
    keyPadSV!.alignment = .Center
    keyPadSV!.distribution = .EqualSpacing
    keyPadSV!.backgroundColor = UIColor.redColor()
    for var k2s = 0; k2s < 5; k2s++ {
        let keyPadSVB = UIStackView(frame:CGRect(x: 0, y: 0, width: 0, height: 0))
        keyPadSVB.axis = .Horizontal
        keyPadSVB.spacing = 0.0
        keyPadSVB.alignment = .Center
        keyPadSVB.distribution = .EqualSpacing
        keyPadSVB.backgroundColor = UIColor.greenColor()
        for var k4s = 0; k4s < 4; k4s++ {
            let button   = UIButton(type: UIButtonType.Custom) as UIButton
            button.frame = CGRectMake(0, 0, 0, 0)
            button.backgroundColor = UIColor.greenColor()
            button.tag =  keyCount
            let blah = "x" + String(keyCount)
            let blahIMAGE = UIImage(named: blah)
            button.setImage(blahIMAGE, forState: UIControlState.Normal)
            button.addTarget(self, action: "keyPadPress:", forControlEvents: UIControlEvents.TouchUpInside)
            keyPadSVB.addArrangedSubview(button)
            keyCount++
        }
        keyPadSV.addArrangedSubview(keyPadSVB)
    }
    keyPadWindow.addSubview(keyPadSV)
    self.view.addSubview(keyPadWindow)
}

它依赖于您有16张图像来显示按键。