开发者

Add subview to UIButton

开发者 https://www.devze.com 2023-03-20 02:55 出处:网络
I\'m trying to add subviews to a UIButton. This is working fine right now. But the button isn\'t clickable anymore as soon as I add the subviews.

I'm trying to add subviews to a UIButton. This is working fine right now. But the button isn't clickable anymore as soon as I add the subviews.

I use the following code:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(column*100+24, row*80+10, 64, 64);
[button addSubview:asyncImage];
[button addSubview:price];
[button addTarget:self开发者_开发问答 
           action:@selector(buttonClicked:) 
 forControlEvents:UIControlEventTouchUpInside];

The button works again if I remove the 2 addSubview: methods. If anyone knows how to fix this it would be great!


I found a quick solutions. I needed to set the asyncImageView to the following:

asyncImage.userInteractionEnabled = NO;
asyncImage.exclusiveTouch = NO;

After this, it worked!


try:

[UIButton buttonWithType:UIButtonTypeCustom];

instead of:

[UIButton buttonWithType:UIButtonControlType];


The important thing here is to make sure that userInteractionEnabled will be set to NO. Fortunately it works immediately for UIImageView and UILabel (maybe for other subclasses of a UIView but those are the most popular subviews added to button) because by default for this classes it is set to NO by default. Unfortunately it is set to YES in UIView so make sure to change it in that case. Messing around with any other flags shouldn't be necessary. The nature of problem is that many people do not know that default value of this flag is different in subclasses.


Have you tried to put:

[asyncImage setUserInteractionEnabled:YES];


in the same sitiation i make this action: inherit from UIButton and add all labels and imageview's of button to self, finally put new button to view as last subview and add targets of self button to this last button(also set backgroundColor to clearColor for transparent). now it will be clickable and works fine.


I added a label to the subview button. For a very long time I was looking for why my text in the button is not clickable. Solution in this thread:

myLable.isUserInteractionEnabled = false 


In Swift, test that is you have your UIButton blocked

uibtn.userInteractionEnabled = false
uibtn.exclusiveTouch = false
0

精彩评论

暂无评论...
验证码 换一张
取 消