class TextFieldWithRemoveButton: UITextField {
private var removeButton: UIButton!
private var buttonWidth: CGFloat {
return removeButton.hidden ? 0 : frame.height
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
removeButton = UIButton(type: .System)
removeButton.setImage(UIImage(named: "RemoveTextIcon"), forState: .Normal)
removeButton.addTarget(self, action: #selector(remove), forControlEvents: .TouchUpInside)
removeButton.tintColor = UIColor.lightGrayColor()
removeButton.hidden = true
addSubview(removeButton)
}
func remove() {
removeButton.hidden = true
text = ""
}
override func layoutSubviews() {
super.layoutSubviews()
removeButton.frame = CGRect(x: frame.width - buttonWidth, y: 0, width: buttonWidth, height: frame.height)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
removeButton.hidden = text!.isEmpty
var rect = super.editingRectForBounds(bounds)
rect.size.width -= buttonWidth / 2
return rect
}
}
Скачать: https://yadi.sk/d/Y-T0m0gyrwuVj