I’ve created a button like so:
UIButton *toTop = [UIButton buttonWithType:UIButtonTypeCustom];
toTop.frame = CGRectMake(12, 12, 37, 38);
toTop.tintColor = [UIColor clearColor];
[toTop setBackgroundImage:[UIImage imageNamed:@"toTop.png"] forState:UIControlStateNormal];
[toTop addTarget:self action:@selector(scrollToTop:) forControlEvents:UIControlEventTouchUpInside];
I have various UIViews that I would like to use this same button over and over again on, but I can’t do it. I’ve tried adding the same UIButton to multiple views but it always just appears on the last place I added it. I’ve also tried:
UIButton *toTop2 = [[UIButton alloc] init];
toTop2 = toTop;
which doesn’t work. Is there an efficient way to do this without setting all the same properties for this same button over and over? Thanks.
UIViews can only ever have a single superview. With the second approach, you are simply allocating a button, then throwing it away and assigning its pointer to point to the first button. So nowtoTopandtoTop2both point to the exact same button instance and you are back to the single superview limitation.So, you’ll need to create separate
UIButtoninstances to accomplish this. One way to do this without duplicating code is to write a category. Something like this should work:UIButton+ToTopAdditions.h:
UIButton+ToTopAdditions.m:
Import
UIButton+ToTopAdditions.h, pass the appropriate target to the method (sounds like that would beselfin your case), and you’ll get as many identical buttons as you need. Hope this helps!