- (IBAction)oneButton1:(id)sender



我是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 函数中更新文本值......

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

这是因为每次您的视图加载它都会创建 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
    }
}

您可以使用一种方法来执行此操作

     - (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;
    }

最新更新