每次按下 UIButton 时如何制作一个新的 UILabel?

How to make a new UILabel every time a UIButton is pressed?

我想在我的程序中添加一个函数,以便每次按下按钮时都会创建一个新标签,我认为最好的方法是拥有一个 UILabel 类型的可变大小数组并添加一个元素每次按下按钮时都添加到数组(一个 UILabel),但是,我不确定该怎么做。

我试过:

var consoleLbl = [UILabel] ()
@IBAction func pushButton(sender: UIButton) {
    consoleLbl[0] = UILabel()
    consoleLbl.frame = CGRect(x:10, y:10, width:10, height:10)
}

但是,我收到以下错误: "Value of optional type 'UILabel?' must be unwrapped to refer to member 'subscript' of wrapped base type 'UILabel'" 如果我加一个“?”要么 ”!”正如它所暗示的那样,我得到了错误: "Value of type 'UILabel' has no subscripts"

你可以试试

 var consoleLbl = [UILabel]()
 var y = 0
 @IBAction func pushButton(sender: UIButton) {
     let lbl = UILabel() 
     lbl.frame = CGRect(x:10, y:y, width:10, height:10)
     lbl.text = "\(y)"
     consoleLbl.append(lbl)
     view.addSubview(lbl)  
     y += 20
 }
 var consoleLbl = [UILabel]()
 var x = Int()
 x = 0

 @IBAction func pushButton(sender: UIButton) {
     let lbl = UILabel() 
     lbl.frame = CGRect(x:x, y:10, width:10, height:10)
     lbl.text = "\(x)"
     consoleLbl.append(lbl)
     view.addSubview(lbl)  
     x += 20 // 10 is width & 10 is gap between two label
 }