ios - 更改在 for 循环中创建的 UIView 的属性

标签 ios swift for-loop

我在我的主视图中添加了几个 UIView,一个挨着另一个,以编程方式,如下所示:

//global variable
var lastLine: UIView!

//inside a function
for(var line = 0; line <= numberOfLines; line++){

        lastLine = UIView(frame: CGRect(x: lengthOfSpace + lengthOfLine * CGFloat(line) + lengthOfSpace * CGFloat(line), y: 8 * view.frame.height/10, width: lengthOfLine, height: 7))
        lastLine.backgroundColor = UIColor.whiteColor()
        lastLine.layer.cornerRadius = lastLine.frame.height/4
        view.addSubview(lastLine)

}

现在我想更改我创建的最后一行的颜色,所以我这样做了:

        lastLine.backgroundColor = UIColor.blueColor()

但是只要我尝试从它们的 for 循环之外更改它,就不会更改任何行的颜色。为什么会这样?有什么办法可以改变线条的颜色吗?

谢谢

最佳答案

问题可能围绕事物的声明方式(单个 View )与事物的创建方式(潜在的 View 数组)展开。为什么不使用 UIView 的标签属性来操作您要更改的特定 View ?

假设您有 5 行/ View ,并希望操纵第 3 行。

创建 5 个 View 的代码:

var numberOfLines:Int = 0

for line in 1...numberOfLines {
    let newView = UIView()
    // code to create and position UIView
    newView.tag = line
    view.addSubview(newView)
}

操作第三行/ View 的代码:

func alterLine(_ lineNumber:Int) {
    for view in view.subviews as [UIView] {
        if view.tag = lineNumber {
            // change view code
        }
    }
}

自从您使用 UIViews 以来,您需要注意任何 View 的标记属性都可能设置为此行号,甚至是 UISlider!为了解决这个问题,您可以子类化 UIView 和 LineView,并且 alterLine() 将是:

func alterLine(_ lineNumber:Int) {
    for view in self.view.subviews as [UIView] {
        if let lineView = view as? LineView {
            if lineView.tag = lineNumber {
                //change LineView code
            }
        }
    }
}

关于ios - 更改在 for 循环中创建的 UIView 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41737262/

相关文章:

ios - 将值传递给更新类、iOS、Swift

ios - 在 swift 中存储/恢复全局字符串数组时出现问题

objective-c - Objective C for 循环延迟

c - 如何在 C 中将 double 组转换为整数数组?

c# - 嵌套的 FOR 循环 : readability & performance

iphone - 为什么 NSUserDefaults 返回一个释放的字符串? (更新#2)

php - 将图像从 iOS 上传到 PHP

ios - 休息套件 0.20 : can not pass in an NSManagedObject to the getObject: method

ios - self 隔离并委托(delegate)奇怪的行为

ios - 当幻灯片拖动时,如何在动态表格 View 单元格的标签上显示幻灯片的当前值?