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

问题描述 投票:0回答:1

一般来说,这是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)不是变量的有效声明。

swift iteration uitextview swift5
1个回答
0
投票

有更简单的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"来实现。

© www.soinside.com 2019 - 2024. All rights reserved.