How can I move the clear button in a UITextField?

前端 未结 7 1583
既然无缘
既然无缘 2021-02-13 13:14

For some reason, when I add a UITextfield as a subview of the contentview of a tablecell, the clearbutton does not align with the text typed in the field, and appears a bit unde

7条回答
  •  醉话见心
    2021-02-13 13:53

    As stated by @Luda the correct way is to subclass UITextField and override - (CGRect)clearButtonRectForBounds:(CGRect)bounds. However the bounds passed in to the method are those of the view itself and not the button. Therefore you should call super to get the OS provided size (to avoid distortion of the image) and then adjust the origin to suit your needs.

    e.g.

    - (CGRect)clearButtonRectForBounds:(CGRect)bounds {
        CGRect originalRect = [super clearButtonRectForBounds:bounds];
        return CGRectOffset(originalRect, -10, 0); //shift the button 10 points to the left
    }
    

    Apple docs state:

    Discussion You should not call this method directly. If you want to place the clear button in a different location, you can override this method and return the new rectangle. Your method should call the super implementation and modify the returned rectangle’s origin only. Changing the size of the clear button may cause unnecessary distortion of the button image.

提交回复
热议问题