2013-06-30 127 views
1

我想知道如何做到這一點,因爲我得到一個錯誤訪問錯誤。如何設置UIButton的titleLabel.text?

在我的應用程序中,我有81 UIButtonsIBAction附加到所有他們的Interface Builder,這IBAction應設置用戶點擊按鈕的文本。我試圖這樣做:

- (IBAction)changeTitle:(UIButton *)button { 
    button.titleLabel.text = [NSString stringWithFormat:@"%@", myString]; 
} 

-(IBAction)setMyString:(id)sender{ 
myString = [NSString stringWithFormat:@"text"]; 
} 

但是,這進入一個錯誤的訪問錯誤,我怎麼能解決這個問題? 百萬謝謝!

錯誤消息:EXC_BAD_ACCESS(代碼= 1,地址=爲0x0) (LLDB)

+0

你需要用完整的錯誤信息更新你的問題。附註 - 不要使用'stringWithFormat:'。你沒有格式化任何東西。直接分配字符串:'button.titleLabel.text = myString;'。 – rmaddy

+0

感謝您的回答!我已經試圖按照你所說的方式來做到這一點,但是它一直給出同樣的錯誤。還有其他選擇嗎? – yeker3

+2

我沒有給你答案。我告訴過你,你需要用完整的錯誤信息更新你的問題。其餘的只是一個建議,而不是試圖解決這個問題。發佈完整的錯誤或者沒有人能夠提供幫助。 – rmaddy

回答

4

您可能會遇到內存管理問題。您沒有使用@property來設置您的實例變量。你正在手動設置它,所以你必須自己管理內存。

-(IBAction)setMyString:(id)sender{ 
    [myString release]; // release old instance 
    myString = [[NSString stringWithFormat:@"text"] retain]; 
} 

,甚至更好,爲你的變量創建一個@property如果你還沒有這樣做的話,通過使用setter方法設置您的變量。像這樣:

@property (copy, nonatomic) NSString *string; // in your @interface 
@synthesize string = myString;    // in your @implementation 

-(IBAction)setMyString:(id)sender{ 
    self.string = [NSString stringWithFormat:@"text"]; // setter will release old value, and retain new value 
} 

- (IBAction)changeTitle:(UIButton *)button { 
    // you should not set the text of the titleLabel directly 
    [button setTitle:self.string forState:UIControlStateNormal]; 
} 
+0

謝謝!我終於跟着第二個選項! – yeker3

5

你不應該去標籤文本直接設置,而使用UIButton setTitle:forState:

- (IBAction)changeTitle:(UIButton *)sender { 
    [button setTitle:myString forState:UIControlStateNormal]; 
} 

label屬性可以用於配置標籤的字體和其他屬性,但其中一些(顏色,陰影顏色和文本)必須使用UIButton方法進行設置。

+0

我改正了,謝謝你的評論。但是,如果這應該解決我的錯誤,它不適合我 – yeker3