In my iPad app, I noticed different behavior between iOS 6 and iOS 7 with UITextFields.
I create the UITextField as follows:
UIButton *theButton = (U
extension UITextField {
/// runtime key
private struct AssociatedKeys {
///
static var toggleState: UInt8 = 0
}
/// prevent multiple fix
private var isFixedRightSpace: Bool {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.toggleState) as? Bool ?? false
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.toggleState, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if self.textAlignment == .right && !isFixedRightSpace {
self.isFixedRightSpace = true
self.addTarget(self, action: #selector(replaceNormalSpacesWithNonBreakingSpaces(textFiled:)), for: UIControl.Event.editingChanged)
}
return super.hitTest(point, with: event)
}
/// replace space to \u{00a0}
@objc private func replaceNormalSpacesWithNonBreakingSpaces(textFiled: UITextField) {
if textFiled.markedTextRange == nil && textFiled.text?.contains(" ") ?? false {
/// keep current range
let editRange = selectedTextRange
textFiled.text = textFiled.text?.replacingOccurrences(of: " ", with: "\u{00a0}")
/// reset this range
selectedTextRange = editRange
}
}
}