通过其标记ID访问动态创建的视图

时间:2016-03-03 17:03:16

标签: swift uiview

有没有办法在其标记ID访问的for循环中创建视图?如果不是有更好的方法来实现以下目标?我的猜测是,因为我覆盖了'myView'var,它始终是for循环的最后一个值。但有没有办法在下面实现这样的目标? [夫特]

var myView = UIView();

// Create a for loop of 20 Views on different x/y axis
var myView = UIView();
var leftPos : CGFloat = 0;
for (var i = 0; i < 20; i++){
    myView.backgroundColor = UIColor.clearColor()
    myView.tag = i;
    myView.frame = CGRect(x: leftPos, y: 0, width: 20, height: 20)
    mySuperView.addSubview(myView)
    leftPos += 20;
}
// Then later on reference it by its tag id:
myView.tag[13].backgroundColor = UIColor.redColor()

2 个答案:

答案 0 :(得分:3)

我建议更好的解决方案是保留您可以通过索引引用的视图数组,而不是使用标记。

// Declare a variable to hold on to your subviews
var views = [UIView]()

// Create 20 views, add them as subviews and add them to the views array
for i in 0..<20 {
    let leftPos = CGFloat(i) * 20

    let view = UIView(frame: CGRect(x: leftPos, y: 0, width: 20, height: 20))
    mySuperView.addSubview(view)
    views.append(view)
}

// Access the view by it's index - no need for a tag.
views[13].backgroundColor = .redColor()

答案 1 :(得分:2)

您可以使用viewWithTag功能找到具有特定标记的视图:

view = mySuperView.viewWithTag(13)

请注意,使用0标记是“坏”,因为如果没有使用其他值,那么这是默认标记值。

相关问题