Override layoutSubviews to call [super layoutSubviews] and then find and reposition the button's view
Solution 1
Find the button you want to move after you call layoutSubviews
because it will be repositioned to where iOS wants it to be every time layoutSubviews
is called.
- (void) layoutSubviews
{
[super layoutSubviews];
for (UIView *view in self.subviews) { // Go through all subviews
if (view == buttonYouWant) { // Find the button you want
view.frame = CGRectOffset(view.frame, 0, -5); // Move it
}
}
}
Solution 2
You can loop through the subviews and compare if the current one is the one you want by using NSClassFromString
, like this for example:
-(void)layoutSubviews {
[super layoutSubviews];
for (UIView *view in self.subviews) {
if ([view isKindOfClass:NSClassFromString(@"TheClassNameYouWant")]) {
// Do whatever you want with view here
}
}
}
You could also use NSLog
in the for loop to see the different subviews.
Eric Brotto
Updated on July 09, 2022Comments
-
Eric Brotto almost 2 years
I'm trying to reposition my
UIBarButtonItem
so that it sits with it's edges against the top and right of the UINavigationBar. I found this accepted answer on how to do this, but I don't really understand how to code it.I've started by creating a new class called
CustomNavBar
which inherits fromUINavigationBar
. I then placed this method in the implementation:- (void) layoutSubviews { }
What I don't understand is the part in the answer that says
call [super layoutSubviews] and then find and reposition the button's view.
How do I code this? Even a nudge in the right direction would be helpful. Thanks!
-
Zappel almost 9 yearsWhy would you ever want to use
NSClassFromString
instead of[TheClassNameYouWant class]
? In the latter case, you would get warnings after a refactor, which you wouldn't in the first case. -
yano over 8 yearsI assume
[TheClassNameYouWant class]
should be more performant as well