所以我在我的应用程序中实现了一个uitextfield,并将其右视图设置为触发某事的按钮。
然而,每当我按下uitextfield的rightView时,它也会触发应用程序开始编辑(键盘显示)。
如何在按下uitextField的rightView时禁用编辑?
感谢。
答案 0 :(得分:1)
使用此自定义子类:
@IBDesignable class TJTextField: UITextField {
fileprivate var ImgIcon: UIImageView?
@IBInspectable var errorEntry: Bool = false {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var leftTextPedding: Int = 0 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var lineColor: UIColor = UIColor.black {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var placeHolerColor: UIColor = UIColor(red: 199.0/255.0, green: 199.0/255.0, blue: 205.0/255.0, alpha: 1.0) {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var errorColor: UIColor = UIColor.red {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var imageWidth: Int = 0 {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable var txtImage : UIImage? {
didSet {
self.setNeedsDisplay()
}
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return self.newBounds(bounds)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return self.newBounds(bounds)
}
fileprivate func newBounds(_ bounds: CGRect) -> CGRect {
var newBounds = bounds
newBounds.origin.x += CGFloat(leftTextPedding) + CGFloat(imageWidth)
return newBounds
}
var errorMessage: String?
override func awakeFromNib() {
super.awakeFromNib()
//setting left image
if (txtImage != nil)
{
let btnLeft = UIButton()
btnLeft.frame = CGRect(x: 0, y: 0, width: CGFloat(imageWidth), height: self.frame.height)
btnLeft.setImage(txtImage, for: .normal)
self.leftViewMode = UITextFieldViewMode.always
self.leftView = btnLeft
btnLeft.addTarget(self, action: #selector(TJTextField.btnClicked), for: .touchUpInside)
}
}
func btnClicked()
{
if !self.isEditing
{
self.resignFirstResponder()
}
}
override func draw(_ rect: CGRect)
{
let height = self.bounds.height
// get the current drawing context
let context = UIGraphicsGetCurrentContext()
// set the line color and width
if errorEntry {
context?.setStrokeColor(errorColor.cgColor)
context?.setLineWidth(1.5)
} else {
context?.setStrokeColor(lineColor.cgColor)
context?.setLineWidth(0.5)
}
// start a new Path
context?.beginPath()
context!.move(to: CGPoint(x: self.bounds.origin.x, y: height - 0.5))
context!.addLine(to: CGPoint(x: self.bounds.size.width, y: height - 0.5))
// close and stroke (draw) it
context?.closePath()
context?.strokePath()
//Setting custom placeholder color
if let strPlaceHolder: String = self.placeholder
{
self.attributedPlaceholder = NSAttributedString(string:strPlaceHolder,
attributes:[NSForegroundColorAttributeName:placeHolerColor])
}
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect
{
return CGRect(x: 0, y: 0, width: CGFloat(imageWidth), height: self.frame.height)
}
}
答案 1 :(得分:0)
确保在向superview添加文本字段后添加按钮视图。在这种情况下,它将重叠文本字段并拦截轻击手势。
或者您可以简单地将约束设置为特定宽度或左侧按钮。