iPhone SDK提供的UIAlertView用以显示消息框,默认的消息框很简单,只需要提供title和message以及button按钮即可,而且默认情况下所有的text是居中对齐的。 那如果需要将文本向左对齐或者添加其他控件,例如输入框时该怎么办呢?不用担心,iPhone SDK还是很灵活的,有很多delegate消息供调用程序使用。所要做的就是在- (void)willPresentAlertView:(UIAlertView *)alertView中按照自己的需要修改即可,例如需要将消息文本左对齐,下面的代码即可实现:
- (void)willPresentAlertView:(UIAlertView *)alertView { for(UIView *view in alertView.subviews) { if([view isKindOfClass:[UILabel class]]) { UILabel *label = (UILabel *) view; label.textAlignment = UITextAlignmentLeft; } } }
这段代码很简单,就是在消息框即将弹出时,遍历所有消息框对象,将其文本对齐属性修改为UITextAlignmentLeft即可。
添加其他组件也一样,如下代码添加两个UITextField:
- (void)willPresentAlertView:(UIAlertView *)alertView { CGRect frame = alertView.frame; frame.origin.y -= 120; frame.size.height += 80; alertView.frame = frame; for(UIView *view in alertView.subviews) { if([view isKindOfClass:[UIButton class]]) { CGRect btnFrame = view.frame; btnFrame.origin.y += 70; view.frame = btnFrame; } } UITextField *accoutName = [[[UITextField alloc] init] autorelease]; UITextField *accoutPassword = [[[UITextField alloc] init] autorelease];; accoutName.frame = CGRectMake(10, 40, frame.size.width - 20, 30); accoutPassword.frame = CGRectMake(10, 80, frame.size.width - 20, 30); accoutName.placeholder = @"Account Name"; accoutPassword.placeholder = @"Password"; accoutName.borderStyle = UITextBorderStyleRoundedRect; accoutPassword.borderStyle = UITextBorderStyleRoundedRect; accoutPassword.secureTextEntry = YES; [alertView addSubview:accoutPassword]; [alertView addSubview:accoutName]; }
对于UIActionSheet其实也是一样的,在- (void)willPresentActionSheet:(UIActionSheet *)actionSheet中做同样的处理一样可以得到自己想要的效果。