2015-05-01 31 views
0

我想在iOS單一視圖應用程序中使用Objective-C來編程一個UIButton來更改UILabel中的文本。有沒有辦法運行一個函數來實現這個在我的「ViewController.m」文件中實現?編程一個UIButton來更改UILabel

這裏是我的源代碼:

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)loadView { 

//UIBUTTON 

//allocate the view 
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 

//set the view's background color 
self.view.backgroundColor = [UIColor whiteColor]; 

//create the button 
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

//set the position of the button 
button.frame = CGRectMake(50, 280, 280, 50); 

//set the font size of the button 
button.titleLabel.font = [UIFont systemFontOfSize:40]; 

//set the text color of the button, before it is pressed 
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; 

//set the text color of the button, while it is pressed 
[button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted]; 

//set the button's title 
[button setTitle:@"3" forState:UIControlStateNormal]; 

//listen for clicks 
[button addTarget:self action:@selector(buttonPressed) 
forControlEvents:UIControlEventTouchUpInside]; 

//add the button to the view 
[self.view addSubview:button]; 

//UILABEL 
UILabel *Question=[ [UILabel alloc] initWithFrame:CGRectMake(10,200,350,60)]; 
[email protected]"How many horns does a Triceratops have?"; 
Question.backgroundColor = [UIColor grayColor]; 
Question.textColor = [UIColor whiteColor]; 
Question.font=[UIFont fontWithName:@"Helvetica" size:18 ]; 
[self.view addSubview:Question]; 
} 

-(void)buttonPressed { } 

@end 

是否有可能引發文本的變化在我的buttonPressed函數?非常感謝任何人的幫助!

回答

1

的問題是,當你創建你的標籤,並將其添加到界面...

UILabel *Question=[ [UILabel alloc] initWithFrame:CGRectMake(10,200,350,60)]; 
// ... 
[self.view addSubview:Question]; 

...你沒有保持對它的引用。所以現在,在buttonPressed,你沒有辦法談論標籤。

使屬性:

@interface ViewController() 
@property (nonatomic, weak) UILabel* questionLabel; 
@end 

...當你創建標籤,記得設置該屬性該標籤。 現在您將可以通過該屬性在buttonPressed(或其他任何地方)訪問該標籤的text

+0

亞光,將您的推薦行應用到「ViewController.h」文件後仍然存在問題。 在我的buttonPressed方法中傳遞命令時,仍然無法更改Question.text。 - (void)buttonPressed {Question.text = @「Correct!」;} 調試器無法識別我的UILabel *問題。 –

+0

我的回答是對的。你現在在做什麼,我不知道。如果你使用我的代碼,這個屬性被稱爲'questionLabel',而不是'Question',不是嗎?顯然你必須編寫有效的代碼;我的解釋是_架構_,但實施取決於你。 - 順便說一句,我沒有說_anything_去_ViewController.h_,我也不建議你這樣做。 – matt

+0

馬特,謝謝你試圖幫助,但我相信你誤解了源代碼。您提出的答案不能解決問題。非常感謝您的幫助。 –

相關問題