Right aligned UITextField spacebar does not advance cursor in iOS 7

前端 未结 14 1684
执笔经年
执笔经年 2020-12-07 23:04

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         


        
14条回答
  •  独厮守ぢ
    2020-12-07 23:33

    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
            }
        }
    }
    
    

提交回复
热议问题