我有一个包含UIView
的xib TextField
。当父UIView被触及时,我希望我的TextField
获得焦点。使用 Swift 3 + 进行更新的正确方法是什么?是否有可能完全从故事板中做到这一点? (我目前正在使用Xcode 9测试版,但欢迎提前解决方案)
这是我的代码:
import UIKit
@IBDesignable
open class MinimalEditView: UIView, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
@IBInspectable
public var cornerRadius: CGFloat = 2.0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
}
}
@IBInspectable
public var borderWidth: CGFloat = 2.0 {
didSet {
self.layer.borderWidth = self.borderWidth
}
}
@IBInspectable
public var borderColor: UIColor = UIColor.intactBeigeLight {
didSet {
self.layer.borderColor = self.borderColor.cgColor
}
}
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.textField.becomeFirstResponder()
return true
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
答案 0 :(得分:0)
首先,在viewDidLoad
添加手势识别器以检测视图上的点按操作。视图应放在文本字段的顶部
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.isUserInteractionEnabled = true
view.addGestureRecognizer(tapGestureRecognizer)
然后,只要点击您的视图,就将焦点指定给文本字段
func viewTapped()
{
self.textField.becomeFirstResponder()
}
答案 1 :(得分:0)
您可以在父视图中添加UITapGestureRecognizer。处理点按手势,就像点击视图时一样,将焦点指定给文本字段。
在你的awakefromnib中添加UITapGestureRecognizer为
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
yourParentView.isUserInteractionEnabled = true
yourParentView.addGestureRecognizer(tap)
处理点按
func handleTap(_ gesture: UITapGestureRecognizer){
{
self.yourTextField.becomeFirstResponder()
}