[英]Swift 5 Can't get variable string from a function chosen from pickerview to update Label.text
[英]How do you change and update a certain character in a String using label and a pickerview in Swift
我有一个 UILabel 当前显示“0000”和一个带有 4 个组件的 pickerView。 每个组件将代表标签中的 4 个字符之一。 因此,组件 1 将更新第一个“0”,第二个组件将更新第二个“0”……依此类推。 我已经成功地使用 obj-c 通过简单地更新字符串来正确更改它们,如下所示:
value = [[NSString alloc] initWithFormat:@"0%@%@%@",
但是当涉及到 Swift 时,我被卡住了。 我可以从字符串中获取字符但不能更新标签。 到目前为止,这是我的代码:
@IBOutlet weak var matchresult: mylabel!
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
var value:String = "0000"
var firstSelection:Int
var secondSelction:Int
var thirdSection:Int
var forthSelection:Int
firstSelection = pickerView.selectedRow(inComponent:0)
secondSelction = pickerView.selectedRow(inComponent:1)
thirdSection = pickerView.selectedRow(inComponent:2)
forthSelection = pickerView.selectedRow(inComponent:3)
//First row selected of first component in pickerview
if firstSelection == 0 {
//Get first character in String 'value'
if var char = value.character(at: 0) {
print("I found \(char)")
//Change the 1st character to 0
char = "0"
print("I changed after\(char)")
//update only the first character in string 'value' with 0
// ???
mylabel.text = value
}
//Second row selected of first component in pickerview
} else if (firstSelection == 1) {
//Get first character in String 'value'
if var char = value.character(at: 0) {
print("I found \(char)")
//Change the 1st character to 1
char = "1"
print("I changed after\(char)")
//update only the first character in string 'value' with 1
// ???
mylabel.text = value
}
}
任何帮助都会很棒。
谢谢
简单的解决方案:
而不是字符串声明一个数组,其中包含选择器视图的 4 个选定值
var selectedValues = ["0", "0", "0", "0"]
并假设这是数据源
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 4
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return numbers.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return numbers[row]
}
在didSelectRow
更新索引处的值,将数组连接到一个字符串并显示它
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedValues[component] = numbers[row]
matchresult.text = selectedValues.joined()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.