如何在UIAlertView中创建自定义UIButton

时间:2011-04-14 22:25:51

标签: iphone objective-c cocoa-touch uibutton uialertview

所以我试图在UIAlertView中嵌入一个toggleable(是一个单词?)“不再显示这个”按钮,但是我遇到了一些我似乎无法解决的麻烦。< / p>

到目前为止,这是我的非工作代码......

编辑:我添加了按钮的方法,并对原始代码进行了一些更改。现在我按下按钮对印刷机作出反应,但结果是崩溃。有什么帮助吗?

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"disclaimer"]){


UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DISCLAIMER" 
                                                message:@"This program is a blah blah"
                                               delegate:self 
                                      cancelButtonTitle:nil
                                      otherButtonTitles:@"I Agree", nil];

UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 230, 260, 50)];
alertLabel.backgroundColor = [UIColor clearColor];
alertLabel.textColor = [UIColor whiteColor];
alertLabel.text = @"Do not show again";
[alert addSubview:alertLabel];
[alertLabel release];

//declared alertCheckboxButton in the header due to errors I was getting when referring to the button in the button's method below
alertCheckboxButton = [UIButton buttonWithType:UIButtonTypeCustom];
alertCheckboxButton.frame = CGRectMake(200, 247, 16, 16);
alertCheckboxButton.backgroundColor = [UIColor clearColor];
UIImage *alertButtonImageNormal = [UIImage imageNamed:@"checkbox.png"];
UIImage *alertButtonImagePressed = [UIImage imageNamed:@"checkbox-pressed.png"];
UIImage *alertButtonImageChecked = [UIImage imageNamed:@"checkbox-checked.png"];
[alertCheckboxButton setImage:alertButtonImageNormal forState:UIControlStateNormal];
[alertCheckboxButton setImage:alertButtonImagePressed forState:UIControlStateHighlighted];
[alertCheckboxButton setImage:alertButtonImageChecked forState:UIControlStateSelected];
[alertCheckboxButton addTarget:self action:@selector(alertCheckboxButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

//made the button a subview of alert rather than alertLabel
[alert addSubview:alertCheckboxButton];  
[alert show];

//moved alertCheckboxButton release to (void)dealloc
[alert release];    

}


-(void)alertCheckboxButtonClicked{

if (![[NSUserDefaults standardUserDefaults] objectForKey:@"disclaimer"]){

    [[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"disclaimer"];
    alertCheckboxButton.selected = YES;
}else {

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"disclaimer"];
    alertCheckboxButton.selected = NO;
    }

}

3 个答案:

答案 0 :(得分:1)

如果要将此按钮设置为切换,则为此按钮分配标签,然后在其事件功能中检查标签是否为0,然后将其设置为1并在那里设置BOOL。当您将其添加到警报时,如果为真,则检查BOOL值是否也会更改按钮图像和标记。

答案 1 :(得分:1)

DUH!我的代码有效。只需删除:@selector(alertCheckboxButtonClicked:)

这不总是简单吗?

答案 2 :(得分:0)

我认为您只想切换UIControl的“selected”属性。当“selected”为YES时,将使用UIControlStateSelected的图像......

复选框的典型iOS等价物是UISwitch,它的“on”属性。