我正在使用Xcode 7.3.1在Swift中编写应用程序以在iOS 9.3上运行。我以编程方式创建UITextFields,但是当我单击其中一个时,无法让它们接受焦点。以下是我创建的每一个的UITextField:如何以编程方式创建可编辑的UITextField
self.hoursField = UITextField()
self.hoursField!.borderStyle = UITextBorderStyle.Bezel
self.hoursField!.canBecomeFirstResponder()
self.hoursField!.canBecomeFocused()
self.hoursField!.delegate = self
self.hoursField!.enablesReturnKeyAutomatically = true
self.hoursField!.translatesAutoresizingMaskIntoConstraints = false
self.hoursField!.userInteractionEnabled = true
的UITextFields似乎正是我想他们,正是看,因为我希望他们看看,我不能让他们接受焦点,所以我可以编辑的文本领域。
我实现在UITextFieldDelegate协议的所有方法,并从所有那些返回一个布尔值的方法返回true。
任何人都可以解释我做错了什么,或不做?
正在创建每个文本字段,并添加到的UIView的定制子类,它包含除的UITextField几个UILabels的。下面是一个创建的文本字段的自定义视图的init方法的相关部分:
init(frame: CGRect, charge: (code:String, note:String?, hours:Int)) {
super.init(frame: frame)
// Create the hours UITextField
self.hoursField = UITextField()
self.hoursField!.borderStyle = UITextBorderStyle.Bezel
self.hoursField!.canBecomeFirstResponder()
self.hoursField!.canBecomeFocused()
self.hoursField!.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
self.hoursField!.delegate = self
self.hoursField!.enablesReturnKeyAutomatically = true
self.hoursField!.font = UIFont.systemFontOfSize(14)
self.hoursField!.keyboardType = UIKeyboardType.NumberPad
self.hoursField!.returnKeyType = UIReturnKeyType.Done
self.hoursField!.text = String(charge.hours)
self.hoursField!.textAlignment = NSTextAlignment.Right
self.hoursField!.translatesAutoresizingMaskIntoConstraints = false
self.hoursField!.userInteractionEnabled = true
// Add it to the view
self.addSubview(self.hoursField!)
// Create its layout constraints
let hoursTopMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: self.hoursField!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.codeLabel!, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
let hoursLeftMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: self.hoursField!, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.codeLabel!, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: self.hourFieldIndent)
let hoursRightMarginConstraint:NSLayoutConstraint = NSLayoutConstraint(item: self.hoursField!, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self.hoursField!, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: self.hourFieldWidth)
// Add the layout constraints to the view
self.addConstraints([hoursTopMarginConstraint, hoursLeftMarginConstraint, hoursRightMarginConstraint])
我的应用程序的简化版本,显示我有可以从https://github.com/ThomBrando/TextFieldDemo.git
这是Stack Overflow上经常被回答的旧的“超视图之外的视图”问题。我标记为重复,所以你有一个链接,我已经在下面的答案中解释了如何清理你的代码,使文本视图变成可点击。 – matt