use*_*743 3 iphone objective-c
我在Objective C中很新,我想我不知道如何处理对象.我创建了一个UILabel,我可以设置文本和其他所有内容.但我想从一个不同的方法更新它..意思我想改变文本,但我没有该方法中的对象!
多数民众赞成我如何设置UILabel
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.view.bounds.size.width / 2), 0.0, 150.0, 43.0) ];
scoreLabel.textAlignment = UITextAlignmentCenter;
scoreLabel.textColor = [UIColor whiteColor];
scoreLabel.backgroundColor = [UIColor redColor];
scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)];
[self.view addSubview:scoreLabel];
scoreLabel.text = [NSString stringWithFormat: @"%d", 0];
}
Run Code Online (Sandbox Code Playgroud)
这就是我想改变UILabel文本的地方
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.crossView.alpha = 0.5;
...change scoreLabel.test
}
Run Code Online (Sandbox Code Playgroud)
这两种方法都在ViewController中!
也许我可以把UILabel绑在自己身上?但怎么样?
Rya*_*anG 10
您需要在.h中为您的UILabel创建一个Property,以便您可以根据ViewController对其进行修改
在你的.h之前添加 @end
@property (strong, nonatomic) UILabel *scoreLabel;
Run Code Online (Sandbox Code Playgroud)
而不是在你的viewDidLoad中这样做:
- (void)viewDidLoad
{
[super viewDidLoad];
_scoreLabel = [ [UILabel alloc ] initWithFrame:CGRectMake((self.view.bounds.size.width / 2), 0.0, 150.0, 43.0) ];
_scoreLabel.textAlignment = UITextAlignmentCenter;
_scoreLabel.textColor = [UIColor whiteColor];
_scoreLabel.backgroundColor = [UIColor redColor];
_scoreLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:(36.0)];
[self.view addSubview:_scoreLabel];
_scoreLabel.text = [NSString stringWithFormat: @"%d", 0];
}
Run Code Online (Sandbox Code Playgroud)
比以后在viewcontroller中:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.crossView.alpha = 0.5;
_scoreLabel.text = @"CHANGED TEXT";
}
Run Code Online (Sandbox Code Playgroud)