iphone - 在 UITextField 中添加按钮

标签 iphone ios sdk uitextfield

我正在开发一个适用于 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/

相关文章:

c++ - UIImage 到 cv::Mat CV_8UC3

android - 在不下载完整操作系统的情况下在eclipse中安装android sdk

android - 无法移开或删除现有 objective-c :\androidSDK\sdk\tools

javascript - 在 tableview 单元格中突出显示 uiwebview 文本

ios - 如何为数组中的每个创建一个具有唯一图像和选择器的自定义 UIButton?

ios - 在 Swift 中连接到互联网时,所有用户如何将 UIViews 发布到单个流?

ios - 带导航 Controller 的模态视图

ios - 如何在选择时为 UICollectionViewCell 内容的扩展设置动画?

ios - 从新 URL 播放视频而不创建新的 AVPlayer 对象

java - 我的 Java SDK 应用程序可以在 BusinessObjects XIr2 中运行吗?