2

我使用以下代码显示带有文本字段的 UIAlertView:

UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Rename", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;

UITextField* textField = [alertView textFieldAtIndex:0];
textField.clearButtonMode = UITextFieldViewModeWhileEditing;

[alertView show];

结果在 iOS 5.1 上如下所示:

在此处输入图像描述

在 iOS 6.1 上:

在此处输入图像描述

如您所见,清除按钮比 iOS 6.1 上的按钮要高一些。知道如何正确居中按钮吗?添加 textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;也无济于事。

(显然,这是 iOS 6.1 中的一个错误,但也许有人知道解决方法。此外,警报视图中文本字段的高度在不同的操作系统版本中似乎也不同,但这是另一个问题。)

4

2 回答 2

2

这看起来像是来自 Apple 的错误,但您始终可以在 textField 中添加自己的清除按钮,执行以下操作:

首先创建一个 UITextField 属性:

@property (nonatomic, strong) UITextField *textField;

然后将其分配给alertView的textField

UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Rename", nil];
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;

self.textField = [alertView textFieldAtIndex:0];
self.textField.delegate = self;

//Create a custom clear button
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 19, 19)];
[button setImage:[UIImage imageNamed:@"clearButton.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(clearText) forControlEvents:UIControlEventAllTouchEvents];

[self.textField setRightView:button];
self.textField.rightViewMode = UITextFieldViewModeAlways;

然后在 clearText 方法中,

- (void)clearText {
    [self.textField setText:@""];
}  

我试过了,它有效

希望这可以帮助

于 2013-02-07T20:24:45.283 回答
0

另一种方法是重写UITextFieldclearButtonRectForBounds :

于 2013-12-11T08:44:41.110 回答