I'm trying to use the rightView
property of the UITextField
class to provide a suffix to a text field. It all seems to work correctly, until I stop editing the text field, at which point the label is moved outside of the UITextField
. The code used is:
class TextFieldWithSuffix: UITextField {
var suffix: String? {
didSet {
let value = self.suffix ?? ""
let label = UILabel(frame: CGRectZero)
label.font = self.font
label.text = value
self.rightView = label
self.rightViewMode = .Always
}
}
override func rightViewRectForBounds(bounds: CGRect) -> CGRect {
var rightViewRect = super.rightViewRectForBounds(bounds)
if let suffix = self.suffix {
let suffixSize = NSString(string: suffix).sizeWithAttributes([NSFontAttributeName: self.font])
rightViewRect.size = suffixSize
}
return rightViewRect
}
}
When the view is first loaded the view looks like below:
However, when the text field has been edited and then the keyboard dismissed, it looked like below:
This has been tested on iOS 7 and 8 and both seem to be doing the same.