我已经将我的视图控制器设置为具有 5 个带有 5 个标签和一个pickerview 的按钮。我希望设置它,以便在单击每个按钮时,它会根据选择的按钮拉出选择器视图,然后选择的选项将显示在按钮旁边的标签中。
为了解决这个问题,我所做的是我的 swift 文件上的 io 插座连接了所有按钮和标签,然后我真的不知道在那之后还能做什么。
我已经研究过是否有其他指南可以连接按钮 + pickerview + 标签的所有三个变量,但没有一个使用按钮作为触发器。
import UIKit
class CalculatorViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!
@IBOutlet weak var thirdButton: UIButton!
@IBOutlet weak var fourthButton: UIButton!
@IBOutlet weak var fifthButton: UIButton!
@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: UITextField!
@IBOutlet weak var thirdTextField: UITextField!
@IBOutlet weak var fourthTextField: UITextField!
@IBOutlet weak var fifthTextField: UITextField!
@IBOutlet weak var pickerView: UIPickerView!
var lastPressedButton: UIButton
override func viewDidLoad() {
super.viewDidLoad()
firstButton.addTarget(self, action:#selector(self.buttonClicked(:)), forControlEvents: .touchUpInside)
secondButton.addTarget(self, action:#selector(self.buttonClicked(:)), forControlEvents: .touchUpInside)
thirdButton.addTarget(self, action:#selector(self.buttonClicked(:)), forControlEvents: .touchUpInside)
fourthButton.addTarget(self, action:#selector(self.buttonClicked(:)), forControlEvents: .touchUpInside)
fifthButton.addTarget(self, action:#selector(self.buttonClicked(:)), forControlEvents: .touchUpInside)
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
}
func buttonAction(sender:UIButton!) {
lastPressedButton = sender
if lastPressedButton == firstButton {
firstTextField.inputView = pickerView
} else if lastPressedButton == secondButton {
secondTextField.inputView = pickerView
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if lastPressedButton == firstButton {
return firstButtonDataSource.count
} else if lastPressedButton == secondButton {
return secondButtonDataSource.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if lastPressedButton == firstButton {
return firstButtonDataSource[row]
} else if lastPressedButton == secondButton {
return secondButtonDataSource[row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if lastPressedButton == first {
self.firstTextField.text = firstButtonDataSource[row]
} else if lastPressedButton == secondButton {
self.secondTextField.text = firstButtonDataSource[row]
}
}
}