2015-04-04 2 views
1

Итак, я новичок в Objective C, XCode iOS, поэтому я начинаю с простого приложения-счетчика.Обновление переменной из другого объекта цели c

У меня есть настройки, основанные на настройке (приращение балла при нажатии кнопки), но я не могу получить текст UILabel для обновления, на каждой кнопке нажмите, т.е. каждый раз, когда я увеличиваю currentScore, он не обновляет currentScore переменная внутри UILabel text

Любая помощь будет высоко оценена!

#import "JPViewController.h" 

@implementation JPViewController 

int currentScore; 

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 

    //Init currentScore 
    currentScore = 0; 
    NSLog(@"Your score is %d", currentScore); 

    //Points text label 

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)]; 
    label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore]; 
    [label setFont:[UIFont boldSystemFontOfSize:16]]; 
    //TODO: Position points in centre. 
    [self.view addSubview:label]; 

    //Add Points Button 

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; 
    [button setTitle:@"Press Me" forState:UIControlStateNormal]; 
    [button sizeToFit]; 
    button.center = CGPointMake(320/2, 60); 
    [button addTarget:self action:@selector(buttonPressed:) 
    forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:button]; 

} 

- (void)buttonPressed:(UIButton *)button { 
    NSLog(@"Button Pressed"); 
    currentScore++; 
    NSLog(@"Your score is %d", currentScore); 
    //TODO: Update the label with the new currentScore here. 
} 

ответ

-1

б в стороне этикетку ваша кнопка сделать следующее вещь

1) Дайте тег на этикетке

UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)]; 
    label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore]; 
    [label setFont:[UIFont boldSystemFontOfSize:16]]; 
    //TODO: Position points in centre. 
    [label setTag:1000];//Give tag to your label 
    [self.view addSubview:label]; 

2) Затем получите ярлык по его методу в методе кнопок

- (void)buttonPressed:(UIButton *)button { 
    NSLog(@"Button Pressed"); 
    currentScore++; 
    NSLog(@"Your score is %d", currentScore); 
    UILabel *label = (UILabel) [self.view viewWithTag:1000]; // you get your label reference here 
    [label setText:[NSString stringWithFormate:%d,currentScore]]; // then store your current score in your lable 
    //TODO: Update the label with the new currentScore here. 
} 

Или это второй метод

1) Сделайте UILabel переменного глобальным, как показано ниже

@implementation JPViewController 
    { 
      UILabel *label; 
    } 

2) в viewDidLoad()

label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)]; 
     label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore]; 
     [label setFont:[UIFont boldSystemFontOfSize:16]]; 
     //TODO: Position points in centre. 
     [self.view addSubview:label]; 

3) В вашей кнопке события

- (void)buttonPressed:(UIButton *)button { 
     NSLog(@"Button Pressed"); 
     currentScore++; 
     NSLog(@"Your score is %d", currentScore); 
     [label setText:[NSString stringWithFormate:%d,currentScore]]; // then store your current score in your lable 
     //TODO: Update the label with the new currentScore here. 
    } 
+0

Немного поправил, но, спасибо! – JP89

+0

Для тех, кто посещает это - не используйте теги для этой ситуации! Второй подход кажется более логичным, однако «метка» определенно не является глобальной переменной. –

+0

@ hris.to спасибо за комментарий, но можете ли вы сказать мне, почему мы не использовали тег? И если мы не используем тег и хотим получить доступ к этому ярлыку в кнопке, как это возможно с помощью тега out или не сделать его глобальным? –

-1

Вы должны создать @property (переменная класса)

@property int currentScore 

@implementation JPViewController 

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 

    //Init currentScore 
    self.currentScore = 0; 
    NSLog(@"Your score is %d", self.currentScore); 

    //Points text label 

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)]; 
    label.text = [NSString stringWithFormat:@"Your score is: %d", self.currentScore]; 
    [label setFont:[UIFont boldSystemFontOfSize:16]]; 
    //TODO: Position points in centre. 
    [self.view addSubview:label]; 

    //Add Points Button 

    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; 
    [button setTitle:@"Press Me" forState:UIControlStateNormal]; 
    [button sizeToFit]; 
    button.center = CGPointMake(320/2, 60); 
    [button addTarget:self action:@selector(buttonPressed:) 
    forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:button]; 

} 

- (void)buttonPressed:(UIButton *)button { 
    NSLog(@"Button Pressed"); 
    self.currentScore++; 
    NSLog(@"Your score is %d", self.currentScore); 
    //TODO: Update the label with the new currentScore here. 
} 
+0

Ах! Благодарю. Единственная проблема заключается в том, что я получаю сообщение об ошибке «Неожиданное @ в программе», когда я пытаюсь создать '@property int currentScore' – JP89

Смежные вопросы