gpt4 book ai didi

swift - 从用户输入刷新 UIPicker

转载 作者:行者123 更新时间:2023-11-30 10:31:22 24 4
gpt4 key购买 nike

我是 Xcode/Swift 新手,正在处理一项需要帮助的作业。我有一个简单的程序,启动时会显示名称列表。我想从 UITextField 中获取一个新名称,并将其添加到当前所选项目之后的选择器数据中。新添加的名称应在选择器中显示为所选项目(因此之前选择的项目将在此时选择器显示屏上紧邻其上方)。到目前为止,我的程序正在运行,但是,我的“picker.reloadAllComponents()”函数似乎破坏了某些东西。当我将其保留在适当位置时,选择器中不会显示任何数据。当我删除它时,我不知道我的 insertButton 操作是否有效。在哪里可以刷新选取器数据,以便在模拟器中看到选取器数据?谢谢。

import UIKit

class ViewController: UIViewController,
UIPickerViewDelegate, UIPickerViewDataSource {

var characterNames = [
"Luke", "Leia", "Han", "Chewbacca", "Artoo",
"Threepio", "Lando"]


@IBOutlet weak var userInput: UITextField!
@IBOutlet weak var picker: UIPickerView!

@IBAction func selectButton(_ sender: UIButton) {
let row = picker.selectedRow(inComponent: 0)
let selected = characterNames[row]
let title = "You selected \(selected)!"

let alert = UIAlertController(
title: title,
message: "Thank you for choosing",
preferredStyle: .alert)
let action = UIAlertAction(
title: "You're welcome",
style: .default,
handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}


@IBAction func insertButton(_ sender: UIButton) {
characterNames.insert(userInput.text!, at: picker.selectedRow(inComponent: 0))
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK:-
// MARK: Picker Data Source Methods

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
return characterNames.count
}

// MARK: Picker Delegate Methods
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
picker.reloadAllComponents()
return characterNames[row]
}
}

最佳答案

不要从 titleRorRow 方法中调用 picker.reloadAllComponents(),因为我认为这可能会调用无限循环 - 此委托(delegate)方法应该返回以下标题:仅该行,因为您的第二行运行正确。因此,将其从那里删除。

相反,在更新源代码后将其放入 insertButton 方法中。这将导致重新加载数据,并再次调用数据源方法来重新填充选取器。

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return characterNames[row]
}


@IBAction func insertButton(_ sender: UIButton) {
characterNames.insert(userInput.text!, at: picker.selectedRow(inComponent: 0))
picker.reloadAllComponents()
}

关于swift - 从用户输入刷新 UIPicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59149490/

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