我创建了一个将值转换为数组的字典。将数组打印到日志会将每个值条目打印为数组中的每个索引。将textview.text
设置为相同的东西(数组中的每个索引)仅打印第一个值。
@IBOutlet weak var snippet: UITextView!
var selectedDictionary = ["firstKey": "firstValue", "secondKey": "secondValue"]
var selectedArray = [String] (selectedDictionary.values)
var numberInArray = selectedArray.count
for var i = 0; i < selectedArray.count; i++ {
println(selectedArray[i])
snippet.text = selectedArray[i]
答案 0 :(得分:2)
您不能迭代每个selectedArray
值来更新TextView文本属性,因为每次for循环找到一个新值时,这将只显示数组中的最后一个值。
相反,您应该尝试使用所有selectedArray
的值构建一个String,然后更新视图文本属性。
你可以这样做:
@IBOutlet weak var snippet: UITextView!
var selectedDictionary = ["firstKey": "firstValue", "secondKey": "secondValue"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var text = ""
var selectedArray = [String](selectedDictionary.values)
for index in 0..<selectedArray.count {
text += "\(selectedArray[index])\n"
}
snippet.text = text
}
答案 1 :(得分:1)
如果您希望它与日志中的显示方式完全相同,请使用:
@IBOutlet weak var snippet: UITextView!
var selectedDictionary = ["firstKey": "firstValue", "secondKey": "secondValue"]
snippet.text = String(format:"%@", selectedDictionary)
答案 2 :(得分:0)
试试这个:
@IBOutlet weak var snippet: UITextView!
var selectedDictionary = ["firstKey": "firstValue", "secondKey": "secondValue"]
var selectedArray = [String] (selectedDictionary.values)
var numberInArray = selectedArray.count
for var i = 0; i < selectedArray.count; i++ {
println(selectedArray[i])
snippet.text += selectedArray[i]
}
答案 3 :(得分:0)
您可以为所有值创建String
,然后遍历您的字典并将每个值附加到创建的字符串,在循环结束后,您可以更新UITextView
。
weak var snippet: UITextView!
var selectedDictionary = ["firstKey": "firstValue", "secondKey": "secondValue"]
var allValues: String = ""
for value in selectedDictionary.values{
if let v = value as String?{
allValues += v
}
}
//set the value of your textview to 'allValues'