1

我是 iOS 新手,我想更新 ViewDidLoad() 函数中的文本。

这是我的按钮功能,单击按钮时会发生动画并将值“1”添加到“resultText.text”

   - (IBAction)oneButton1:(id)sender {
    oneBtn2.userInteractionEnabled = YES;
    CGRect frame = oneBtn1.frame;
    CGRect frame1 = reffButton.frame;
    frame.origin.x = frame1.origin.x; 
    frame.origin.y = frame1.origin.y; 

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 3.0];

    [UIView animateWithDuration:3.0 animations:^{
        [oneBtn1 setTransform:CGAffineTransformMakeScale(.4, .4)];
    } completion:^(BOOL finished) {
        oneBtn1.hidden = YES;
        price = [resultText.text intValue];

        [resultText setText:[NSString stringWithFormat:@"%i", price+1]];

      }];
    oneBtn1.frame = frame;
    [UIView commitAnimations];

}

问题:上面的文本值为 1 但在 ViewDidLoad 中为 0 ,

 - (void)viewDidLoad
 {
[super viewDidLoad];

 NSLog(@"%@", resultText.text); // output is 0 instead of 1;

}

请任何人告诉我如何更新 ViewDidLoad 函数中的文本值...

4

3 回答 3

7

ViewDidLoad 仅在对象创建时调用一次。因此您无法更新 ViewDidLoad 中的内容。ViewDidLoad 用于初始化参数并在创建对象时设置初始设置。

于 2013-09-23T06:32:34.277 回答
1

这是因为每次您的视图加载它都会创建您的 textField 的新对象,这就是为什么您无法获取以前的(因为它的新 textField 不是旧的)。所以您必须将您的文本保存在某个地方,例如您可以使用NSUserDefaults

设置文本

NSString *result=[NSString stringWithFormat:@"%i", price+1];

[resultText setText:];

//Also set it to NSUserDefaluts
[[NSUserDefaults standardUserDefaults] setValue:result forKey:@"key"];
[[NSUserDefaults standardUserDefaults] synchronize];

获取文本

- (void)viewDidLoad
{
    [resultText setText:[[NSUserDefaults standardUserDefaults] valueForKey:@"key"]];
    NSLog(@"%@", resultText.text); 
}

编辑

您可以在按钮单击后制作动画,因此在按钮单击事件中调用此方法

-(void)animateImage
{
    if ([resultText.text isEqualToString:@"3"]) {
        //make your animation
    }
}
于 2013-09-23T06:45:45.793 回答
0

您可以使用一种方法来做到这一点

     - (void)updateLabel {
        oneBtn2.userInteractionEnabled = YES;
        CGRect frame = oneBtn1.frame;
        CGRect frame1 = reffButton.frame;
        frame.origin.x = frame1.origin.x; 
        frame.origin.y = frame1.origin.y; 

        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration: 3.0];

        [UIView animateWithDuration:3.0 animations:^{
            [oneBtn1 setTransform:CGAffineTransformMakeScale(.4, .4)];
        } completion:^(BOOL finished) {
            oneBtn1.hidden = YES;
            price = [resultText.text intValue];

            [resultText setText:[NSString stringWithFormat:@"%i", price+1]];

          }];
        oneBtn1.frame = frame;
        [UIView commitAnimations];

   }


     - (void)viewDidLoad
     {
    [super viewDidLoad];
     [self updateLabel];
     NSLog(@"%@", resultText.text); // output is 0 instead of 1;

    }
于 2013-09-23T09:53:25.857 回答