nicael
nicael

Reputation: 19005

Is there a better way to remove a last subview from view

To remove last subview from a view, I use

[[[self.view subviews] lastObject] removeFromSuperview];

I'd use removeLastObject, but can't as subviews is readonly immutable array.

So I need to:

It works, but is there a better way? This seem to be a bit unnatural. I look for something like [self.view removeLastSubview], but unfortunately it doesn't exist.

Upvotes: 3

Views: 1063

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

To avoid Objective-C's message-sending syntax

Note: dont do that

UIView *lastView = self.view.subviews[self.view.subviews.count-1];
lastView.removeFromSuperview;

I said: dont do that

but seriously:

[[[self.view subviews] lastObject] removeFromSuperview];

is just fine. I'd consider the first snippet code-smell.

Upvotes: 3

arturdev
arturdev

Reputation: 11039

Make a category

@interface UIView (Exptened)

- (void)removeLastSubView;

@end

@implementation UIView(Exptened)

- (void)removeLastSubView
{
    [[[self subviews] lastObject] removeFromSuperview];
}

@end

Upvotes: 1

Related Questions