UIPickerView,每个组件都包含一个UIButton

时间:2019-03-15 19:47:00

标签: uibutton uipickerview

我正在尝试创建按钮的pickerview,即每个组件都包含一个按钮。我希望能够像在标签上一样,将一个按钮添加到viewForRow委托方法中。当我这样做时,该按钮会正确显示,但无法单击。我究竟做错了什么?这是我的代码:

import UIKit

class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {

var pickerData: [String] = [String]()
@IBOutlet weak var pickerView: UIPickerView!

func numberOfComponents(in pickerView: UIPickerView) -> Int {

    return 1

}

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    return pickerData.count
}


    override func viewDidLoad() {
    super.viewDidLoad()
    self.pickerView.delegate = self
    self.pickerView.dataSource = self
    pickerData = ["א","ב","ג","ד","ה"]

    // Do any additional setup after loading the view, typically from a nib.
}


func pickerView(_ pickerView: UIPickerView,     rowHeightForComponent component: Int) -> CGFloat {
    return 120
 }


func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle(pickerData[row], for: .normal)
button.addTarget(self,    action:#selector(self.buttonPressed), for: .touchUpInside)
self.pickerView.addSubview(button)
return button


}

func pickerView(_ pickerView: UIPickerView,   didSelectRow row: Int, inComponent component: Int) {

print ("Selected \(pickerData[row])")

}

@objc func buttonPressed(sender:UIButton) {

print ("Button pressed!")


}


}

0 个答案:

没有答案