2011-04-14 98 views
7

所以我試圖嵌入一個切換(是一個單詞?)在UIAlertView中,「不要再顯示這個」按鈕,但我遇到了一些麻煩,我可以似乎沒有得到解決。如何在UIAlertView中創建一個自定義的UIButton

這是迄今爲止我不工作的代碼...

編輯:我添加的按鈕的方法,並提出在原來代碼中的一些變化。現在我得到按鈕來對新聞作出反應,但結果是崩潰。任何幫助?

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; 
    } 

} 

回答

1

如果你想使這個按鈕,撥動然後將標籤分配到該按鈕,然後在其事件功能檢查代碼是否爲0,那麼將它設置爲1,並且還設置有BOOL。當你將它添加到警報中時,如果是true,檢查BOOL值是否改變你的按鈕圖像和標籤。

+0

如何更改按鈕的狀態?在我的代碼中,如果我點擊它,沒有任何反應,即我沒有看到不同的PNG,我只是看到相同的控制狀態正常的圖像。我知道如何使用IB來做到這一點,但我不知道如何以編程方式更改按鈕狀態。 – Sam 2011-04-15 19:22:13

0

我想你只是想切換UIControl的「selected」屬性。當「selected」是YES時,將使用UIControlStateSelected的圖像...

複選框的典型iOS等價物是UISwitch,它具有「on」屬性。

+0

請允許我問,是否有更好的方式在啓動時顯示免責聲明,理想情況下不會再顯示? (直到更新或重新安裝或甚至像這樣,我猜測會擦除userdefaults)是一個更接受的方式來執行操作表或其他功能嗎?我是否浪費了大量時間試圖弄清楚這個按鈕的事情,只是爲了讓最終看起來有些不自然,而我的所有用戶都說「Ida就是這樣做的......」? – Sam 2011-04-17 01:20:36

1

DUH!我的代碼有效。只需要刪除:in @selector(alertCheckboxButtonClicked :)

難道這不總是簡單嗎?

相關問題