Prevent user from setting cursor position on UITextField

后端 未结 6 951
执念已碎
执念已碎 2020-12-17 17:03

I have an UITextField constructed using the storyboard. I want to not allow the user to change the position of the cursor and keep it always at the end of the text into the

6条回答
  •  情书的邮戳
    2020-12-17 17:21

    Simply create a subclass of UITextField and override the closestPositionToPoint method:

    - (UITextPosition *)closestPositionToPoint:(CGPoint)point{
        UITextPosition *beginning = self.beginningOfDocument;
        UITextPosition *end = [self positionFromPosition:beginning offset:self.text.length];
        return end;
    }
    

    Now the user will be unable to move cursor, it will be always in the end of field.

    SWIFT:

    override func closestPosition(to point: CGPoint) -> UITextPosition? {
        let beginning = self.beginningOfDocument
        let end = self.position(from: beginning, offset: self.text?.count ?? 0)
        return end
    }
    

提交回复
热议问题