Modifying UIButton's alpha property from another class

 ̄綄美尐妖づ 提交于 2019-12-01 09:38:33

问题


I'm trying to change the alpha of an UIButton from another class. The function that is called in set the alpha property of my UIButton is actually called because I've put a NSLog there and I can see how it works. I'd be thankful if you could give me any suggestion.

Here's my current code.

ViewController.h

- (void) setAlphaToButton;

@property (strong, nonatomic) IBOutlet UIButton *myButton;

ViewController.m

@synthesize myButton;

- (void) setAlphaToButton {
    myButton.alpha = 0.5;
    NSLog(@"Alpha set");
}

ImageViewSubclass.m

- (void) tapDetected:(UITapGestureRecognizer *)tapRecognizer {
    ViewController *VC = [[ViewController alloc] init];
    [VC setAlphaToButton];
}

And when the image view is pressed, in my console I get: Alpha set. And the button doesn't change.


回答1:


In your code, an instance of ViewController is alloced and inited, and the method setAlphaToButton is called on it. Then the view controller is released because you have no object retaining it. That's why you don't see any effect; the ViewController instance you call the method on never appears on screen.

It's not clear how your code is supposed to work; do you have an instance of ViewController in existence when tapDetected is called? If this is the case, and this is the ViewController whose button you want to alter the alpha of, then you need to have a reference to that instance of ViewController and call setAlphaToButton on it.




回答2:


Your view is not loaded at the moment you trying to set alpha! You need to call this method after your viewDidLoad fired. You can force it by calling view, but it's kind of hackand not recommended!

MyViewController *vc = [MyViewController new];
vc.view; // this string will force view loading 
[vc setAlphaToButton];



回答3:


Add a property of uiviewcontroller class in imageviewsubclass as

ImageViewSubclass.h
@propery (nonatomic, retain) uiviewController *parent;
ImageViewSubclass.m
@synthesize parent;

And initialize it with "self" in view controller class when initalize object of imageviewsubclass and add on the view like

ImageViewsubclass *oneObj = [ImageViewsubClass alloc] init];
oneOBj.parent = self;

do the same for all objects of ImageviewsubClass objects.

and in

- (void) tapDetected:(UITapGestureRecognizer *)tapRecognizer {
    [parent setAlphaToButton];
}


来源:https://stackoverflow.com/questions/15044677/modifying-uibuttons-alpha-property-from-another-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!