我想制作一个UIAlertView,其中有一个UITextFieldUITextView显示5-6行。我尝试创建视图并将其添加为子视图,但它与警报视图的按钮重叠。调整警报视图的大小时,按钮不会向下移动。另外,我需要为此设置不同的背景和内容。那就是我需要创建一个自定义警报视图。我是iPhone编程的新手。请提供一种方法。

最佳答案

您确实无法创建自定义警报视图,因为Apple决定这是他们不希望我们遇到的问题。如果您只能使用警报中的一个文本字段和库存背景颜色,则可以使用setAlertViewStyle:UIAlertViewStylePlainTextInput将文本字段放入警报中。

UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
[myAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
[myAlertView show];


但是,如果您确实要进行这些更改,则必须使用UIView进行自己的更改并进行修饰,使其看起来像是警报视图。这是一个粗糙的例子:

- (IBAction)customAlert:(UIButton *)sender
{
    UIView *myCustomView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 280, 300)];
    [myCustomView setBackgroundColor:[UIColor colorWithRed:0.9f green:0.0f blue:0.0f alpha:0.8f]];
    [myCustomView setAlpha:0.0f];

    UIButton *dismissButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [dismissButton addTarget:self action:@selector(dismissCustomView:) forControlEvents:UIControlEventTouchUpInside];
    [dismissButton setTitle:@"Close" forState:UIControlStateNormal];
    [dismissButton setFrame:CGRectMake(20, 250, 240, 40)];
    [myCustomView addSubview:dismissButton];

    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, 240, 35)];
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    [myCustomView addSubview:textField];

    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 75, 240, 150)];
    [myCustomView addSubview:textView];

    [self.view addSubview:myCustomView];

    [UIView animateWithDuration:0.2f animations:^{
        [myCustomView setAlpha:1.0f];
    }];
}

- (void)dismissCustomView:(UIButton *)sender
{
    [UIView animateWithDuration:0.2f animations:^{
        [sender.superview setAlpha:0.0f];
    }completion:^(BOOL done){
        [sender.superview removeFromSuperview];
    }];
}

10-08 08:20
查看更多