我有一个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
}
}
任何帮助都会很棒。
谢谢
答案 0 :(得分:0)
简单的解决方案:
而不是字符串,而是声明一个数组,其中包含选择器视图的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()
}