如何移动 UITextField 中的清除按钮?
由于某种原因,当我添加 UITextfield 作为表格单元格内容视图的子视图时,清除按钮与字段中键入的文本不对齐,并且出现在其下方。有什么方法可以移动清除按钮的文本来阻止这种情况发生吗?感谢您的帮助,
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 underneath it. Is there any way I can move the text of the clearbutton to stop this from happening? Thanks for any help,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
Swift 4 版本是
Swift 4 version would be
我对
UITextField
进行了子类化并覆盖了clearButtonRectForBounds:
函数。.h
.m
I had subclassed the
UITextField
and override the functionclearButtonRectForBounds:
..h
.m
我还没见过这个,屏幕截图会很有帮助。但是,快速的答案是,您可以检查 UITextField 的子视图数组,找到包含清除按钮的子视图,并调整其frame.origin。
编辑:看来我对这个答案(写于 2010 年)被否决了。这不是“官方”批准的方法,因为您正在操纵私有对象,但 Apple 无法检测到它。主要风险是视图层次结构可能会在某个时刻发生更改。
I haven't seen this, and a screen shot would be helpful. But, the quick answer is that you can inspect the subviews array of the UITextField, find the subview that contains the clear button, and adjust its frame.origin.
Edit: It seems I've been downvoted for this answer (written in 2010). This is of not an "officially" approved method because you're manipulating private objects, but it's not detectable by Apple. The main risk is that the view hierarchy might be changed at some point.
子类 UITextField 并重写此方法:
返回符合您需求的 CGRect。
Subclass UITextField and override this method:
return the CGRect that matches your needs.
正如 @Luda 所说,正确的方法是子类化 UITextField 并覆盖
- (CGRect)clearButtonRectForBounds:(CGRect)bounds
。然而,传递给该方法的边界是视图本身的边界,而不是按钮的边界。因此,您应该调用super
来获取操作系统提供的大小(以避免图像失真),然后调整原点以满足您的需要。例如
苹果 文档指出:
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 callsuper
to get the OS provided size (to avoid distortion of the image) and then adjust the origin to suit your needs.e.g.
Apple docs state:
Van Du Tran 在 Swift 4 中的答案:
}
The answer from Van Du Tran in Swift 4:
}
斯威夫特 4、5
Swift 4, 5