سؤال

Hello I have a problem with an added subview. I have this code in method1:

UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                    initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
spinner.center = CGPointMake(160, 500);
spinner.hidesWhenStopped = YES;
[self.view addSubview:spinner];
[spinner startAnimating];

and I want to add

[spinner stopAnimating]

on another method2.

How do I do so?

هل كانت مفيدة؟

المحلول

In your .m file (no need to do this in .h unless you need to do this from another class):

@interface MyClass ()

@property (strong, nonatomic) UIActivityIndicatorView *spinner;

@end

@implementation MyClass

- (void)someMethod
{
    // where you were calling the code from your post, do this:
    self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.spinner.center = CGPointMake(160, 500);
    self.spinner.hidesWhenStopped = YES;
    [self.view addSubview:self.spinner];
    [self.spinner startAnimating];
}

- (void)someOtherMethod
{
    [self.spinner stopAnimating];
}

نصائح أخرى

The problem is that you set up the spinner in your code without keeping a reference to it. Thus, another method can't find it. You have two choices:

  • Assign spinner to an instance variable when you create it so that another method can use that instance variable to access the spinner

  • Give spinner a tag so that another method can find it as a subview of your view by its tag

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top