gpt4 book ai didi

ios - 如何在 Swift 中使用标签和 pickerview 更改和更新字符串中的某个字符

转载 作者:行者123 更新时间:2023-11-29 05:12:56 25 4
gpt4 key购买 nike

我有一个当前显示“0000”的 UILabel 和一个包含 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

}

}

任何帮助都会很棒。

谢谢

最佳答案

简单的解决方案:

声明一个数组,而不是一个字符串来保存选择器 View 的 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()
}

关于ios - 如何在 Swift 中使用标签和 pickerview 更改和更新字符串中的某个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com