Swift:点击 UITextField 时如何显示 UIPickerView
Posted
技术标签:
【中文标题】Swift:点击 UITextField 时如何显示 UIPickerView【英文标题】:Swift: how to show UIPickerView when a UITextField is tapped 【发布时间】:2015-09-14 16:38:44 【问题描述】:在我的 ios 应用程序中有一个表格,其中一些单元格包含一个 UITextField,我希望当点击该 UITextField 时,它的 UIPiCkerView 被选中,并且在选择后 UIPickerView 应该消失。在this 教程之后,我编写了以下类,表示具有选择器视图的单元格:
import Foundation
import UIKit
class PickerCell: UITableViewCell, UIPickerViewDataSource,UIPickerViewDelegate, UITextFieldDelegate
@IBOutlet weak var label : UILabel!
@IBOutlet var myPicker: UIPickerView! = UIPickerView()
@IBOutlet weak var selectedData: UITextField!
var pickerData:[String]!
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
return 1
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
return pickerData.count
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
return pickerData[row]
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
self.selectedData.text = self.pickerData[row]
self.myPicker.hidden = true;
func configurePickerCell(labelText:String, enabled:Bool, defaultValueIndex:Int)
self.label.text = labelText
var labelFrame:CGRect = self.label.frame
labelFrame.size.height = Settings.labelHeight
self.label.frame = labelFrame
self.myPicker.delegate = self
self.myPicker.dataSource = self
self.selectedData.delegate = self
self.setEditable(enabled)
func setEditable(canEdit:Bool)
if (canEdit)
self.selectedData.userInteractionEnabled = true
self.label.highlighted = false
self.selectedData.layer.borderColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1).CGColor
else
self.selectedData.userInteractionEnabled = false
self.label.highlighted = true
self.selectedData.layer.borderColor = UIColor(red: 176/255, green: 176/255, blue: 176/255, alpha: 1).CGColor
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
self.myPicker.hidden = false
return false
但我认为我遗漏了一些东西,因为当我点击 UITextView 时,UIPickerView 没有出现,但光标显示在其中。我错过了什么?
【问题讨论】:
只需让选择器查看文本字段的inputView
。无需显示或隐藏选择器。
如果您想将此评论设置为答案,我会将其设置为“答案”:)
【参考方案1】:
首先你的数据和 uiviewController 在哪里? 你的pickerView是正确的,但你应用在哪里?
尝试像这样开始你的课程 类 ViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource , CLLocationManagerDelegate
而不是“类 PickerCell:UITableViewCell” 你使用“tableViewCell”来创建一个pickerView这不是一个好主意
【讨论】:
以上是关于Swift:点击 UITextField 时如何显示 UIPickerView的主要内容,如果未能解决你的问题,请参考以下文章
Swift:UITextField 在第一次被点击时被立即关闭