你能推荐一些我可以使用的东西吗?
我将通过presentViewController:animated:completion: (ios 5+) 或presentModalViewController:animated: ios <5 (deprecated) 呈现模态视图
如果您想坚持使用 alertview,您可以在 cocoacontrols.com 上找到替代品。
From the docs:
子类化注释
UIAlertView 类旨在按原样使用,不支持子类化。此视图层次结构
类是私有的,不能修改。
添加文本视图会修改视图层次结构,并可能导致应用商店提交被拒绝。
使用this category,您可以轻松检查任何视图的视图层次结构。 (或在调试器控制台上使用po [alertView recursiveDescription])
注意:这是绝对不能在实际应用程序中使用的代码。
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title"
message:@"msg"
delegate:nil
cancelButtonTitle:@"ok"
otherButtonTitles: nil];
UITextField *textFiled = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
[textFiled setText:@"dont try that at home"];
[alertView addSubview:textFiled];
[alertView show];
[alertView printSubviewsWithIndentation:4];
我们将记录这个层次结构
[0]: class: 'UIImageView'
[1]: class: 'UILabel'
[2]: class: 'UILabel'
[3]: class: 'UIAlertButton'
[0]: class: 'UIImageView'
[1]: class: 'UIButtonLabel'
[4]: class: 'UITextField'
导致这个
textView 只是放置在所有其他视图之上。实际上它必须放在[2]: class: 'UILabel' 下。我们可以通过摆弄视图层次结构(循环并重新排列它)或通过子类化 UIAlertView 并覆盖layoutSubviews 来做到这一点。这两件事,苹果都不想要。
所以总结一下,如果涉及到 UIAlertView,你有 3 个选择:
- 照原样接受它(请记住,某些形式的输入可通过预定义的样式获得)
- 使用其他视图控制器来呈现模态视图
- 使用替代品。但不是 UIAlertView 的子类。
但是,如果有人仍然相信弄乱视图层次结构是一个好主意并且比我和苹果的工程师更了解,这里是代码
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title"
message:@"Please read carefully the next 3 lines"
delegate:nil
cancelButtonTitle:@"ok"
otherButtonTitles: nil];
[alertView show];
CGFloat height = 25.0;
UILabel *msgLabel = [[alertView subviews] objectAtIndex:2];
UITextField *textField1 = [[UITextField alloc] initWithFrame:CGRectMake(msgLabel.frame.origin.x, msgLabel.frame.origin.y+msgLabel.frame.size.height, msgLabel.frame.size.width, height)];
[textField1 setText:@"dont try that at home"];
[textField1 setBackgroundColor:[UIColor whiteColor]];
UITextField *textField2 = [[UITextField alloc] initWithFrame:CGRectOffset(textField1.frame, 0, height + 4)];
[textField2 setText:@"REALLY! dont try that at home"];
[textField2 setBackgroundColor:[UIColor whiteColor]];
UITextField *textField3 = [[UITextField alloc] initWithFrame:CGRectOffset(textField2.frame, 0, height + 4)];
[textField3 setText:@"REALLY! dont try that at home"];
[textField3 setBackgroundColor:[UIColor whiteColor]];
NSArray *followringSubviews = [[alertView subviews] subarrayWithRange:NSMakeRange(3, [[alertView subviews] count] - 3)];
[followringSubviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) {
view.frame = CGRectOffset(view.frame, 0, 3*height);
}];
[alertView addSubview:textField1];
[alertView addSubview:textField2];
[alertView addSubview:textField3];
alertView.frame = CGRectUnion(alertView.frame, CGRectOffset(alertView.frame, 0, 80));
结果: