繁体   English   中英

根据数组中的项目数迭代创建 UITextViews

[英]Iteratively creating UITextViews based on number of items in an array

如果这是一个基本问题,那么对于 swift 和一般编码来说很新,所以很抱歉,但我希望能够根据字符串数组中的项目数在程序上创建 UITextViews。 例如:

var stringArray = [“first sentence string”, “second sentence string”] 
//create two UITextViews with text property of “first sentence string” and “second sentence string”

在这种情况下,手动创建两个 UITextViews 来放入字符串并不太难,但我希望能够使用 stringArray 所需的尽可能多的文本视图来更新我的视图,其中 stringArray 将有不同数量的项目.

我的第一个想法是迭代创建 UITextView 的变量的名称,例如:

for i in stringArray {
   var textView(i) = UITextView()
   //textView properties inserted here
   view.addSubView(textView(i))
}

但这不起作用,因为 textView(i) 不是变量的有效声明。

有更简单的 Swifty 方法来解决这个问题,但如果你只是想学习,你可以这样做:

for i in 0 ..< stringArray.count {
    let text = stringArray[i]
    // Set some fixed height for the textView so you can space it out by that height
    let textViewHeight: CGFloat = 50.0
    let textView = UITextView()
    view.addSubview(textView)
    textView.frame = CGRect(x: 0, y: CGFloat(i)*textViewHeight, width: view.frame.width, height: textViewHeight)
    textView.text = text
}

听起来您的问题来自尝试命名属性textView(i) 您不能将变量传递给属性的名称。 在这种情况下,您甚至不需要跟踪 textView 的迭代(即textView1textView2等),因为一旦循环的迭代完成,您将不再拥有对它的引用。 如果你想参考这些,你可以添加一个 TextViews 数组作为实例属性,如下所示:

var stringArray = ["first sentence string", "second sentence string"]

var textViews = [UITextView]()

for i in 0 ..< stringArray.count {
    let text = stringArray[i]
    // Set some fixed height for the textView so you can space it out by that height
    let textViewHeight: CGFloat = 50.0
    let textView = UITextView()
    view.addSubview(textView)
    textView.frame = CGRect(x: 0, y: CGFloat(i)*textViewHeight, width: view.frame.width, height: textViewHeight)
    textView.text = text
    // Append the textView to the array
    textViews.append(textView)
}

现在您可以访问数组中的任何和所有 textView。 在您的代码中的某个地方说,您想访问 textViews 数组中的第 n 个 textView 并更改它的文本,您可以通过说textViews[n].text = "updated text"来完成此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM