我正在开发一个适用于 iOS 的浏览器应用程序,并且希望在地址栏的文本字段内添加一个“阅读器”按钮,就像 Mobile Safari 在检测到该页面是一篇文章时所做的那样。 在 UITextField 右侧添加按钮的好方法是什么?
最佳答案
您可能想要使用 UITextField 的 rightView
属性。基本上,有两个属性(相应的这个属性和 leftView
)允许您将自定义 View /控件放置在 UITextField 内。您可以通过 rightViewMode
/leftViewMode
属性控制是否显示这些 View :
UIButton *myButton = [UIButton new];
// configure your button here
myTextField.rightView = myButton;
myTextField.rightViewMode = UITextFieldViewModeUnlessEditing; // check the docs for other possible values
此外,还有一个名为 rightViewRectForBounds:
的方法,它返回自定义 View /控件所在的 CGRect。你不应该直接在那里传递你的按钮的尺寸,相反,如果你想放置一些肯定大于此方法返回的矩形的东西(似乎当你在其中放置 View 时 UITextField 代表你调用它),你的 View 将缩放以适合该矩形。在这种情况下,您可能想要覆盖它(创建您的类别或 UITextField 的子类。假设您选择一个类别,您的 UITextField+MyButton 应该如下所示:
@interface UITextField(MyButton)
- (CGRect)rightViewRectForBounds:(CGRect)bounds;
@end
@implementation UITextField(MyButton)
- (CGRect)rightViewRectForBounds:(CGRect)bounds
{
// return the CGRect that would fit your view/button. The buttons param that is passed here is the size of the view that is being added to the textField.
}
// possibly some other methods that you override
@end
希望这有帮助。正如其他答案中所述,请先查看文档,看看有哪些方法可以帮助您。
关于iphone - 在 UITextField 中添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8927505/