【问题标题】:Assigning tag to UIButton while loop from array从数组循环时将标签分配给UIButton
【发布时间】:2016-08-09 22:31:48
【问题描述】:

如何在数组中的循环中为 UIButton 分配唯一标签:

var buttonArray: NSMutableArray = ["one", "two", "Three"] // it is a mutable array but for illustration purposes only I put this....
for btnName in buttonArray {

    let button = UIButton(frame: CGRectMake(0,0,100,100))

    button.layer.masksToBounds = true
    button.layer.cornerRadius = 20
    button.setTitle("\(btnName)", forState: UIControlState.Normal)

    //button.tag = ??????

    print(button.tag)

}

【问题讨论】:

    标签: ios uibutton swift2


    【解决方案1】:

    或者,您可以使用enumerate()。这将创建一个惰性序列,其中包含一对元素及其索引。

    例如:

    for (index, btnName) in buttonArray.enumerate() {
    
        let button = UIButton(frame: CGRectMake(0,0,100,100))
    
        ...
    
        button.tag = index
    }
    

    【讨论】:

    • 这个实现起来其实更优雅
    【解决方案2】:

    显然你可以注入一些计数器。

    var cnt = 0
    for btnName in buttonArray {
        let button = UIButton(frame: CGRectMake(0,0,100,100))
        button.tag = cnt
        cnt += 1
    }
    

    【讨论】:

    • 我认为 ++ 在 swift 中是不允许的...我尝试了 cnt+=1 然后 button.tag = cnt 并工作...如果你更新你的答案,我会接受它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    相关资源
    最近更新 更多