Trouble with autoresizingMask and fixed margins
-
09-10-2019 - |
Question
I'm trying to get this to work with code in a ViewController's view:
but I can't get it to work.
I've tried
-(void)loadView {
UIView *contentView = [[[UIView alloc] init] autorelease];
self.view = contentView;
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(5,5,0,100);
button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[contentView addSubview:button];
}
but the width of the button is still the width of the superview...
I'm sure there's an easy explanation.
Thanks, everybody!
Antonio
Solution
-initWithFrame:
is the designated initializer for UIView. On the Mac side (NSView) I know strange things can happen when using -init
instead of -initWithFrame:
. Perhaps this is the problem?
OTHER TIPS
Instead of bothering with the autoresizingMask
flag, I override layoutSubviews
in custom UIView
subclass:
- (void)loadView { self.view = [ContentView view]; self.view.frame = CGRectMake(0, 0, 30, 100); }
where ContentView
is defined as:
@interface ContentView : UIView { UIButton *button; } + (id)view; @end @implementation ContentView { + (id)view { return [[self new] autorelease]; } - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { button = [UIButton buttonWithType:UIButtonTypeCustom]; [self addSubview:button]; // Retains the button. } return self; } - (void)layoutSubviews { const CGFloat margin = 5; CGRect size = self.frame.size; button.frame = CGRectMake(margin, margin, size.width - 2 * margin, size.height - 2 * margin); } }
Try this code.
- (void)loadView
{
CGRect screenBounds = [UIScreen mainScreen].bounds;
UIView *contentView = [[[UIView alloc] initWithFrame:screenBounds] autorelease];
self.view = contentView;
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(5,5,screenBounds.size.width - 10,100);
[button setTitle:@"hello" forState:UIControlStateNormal];
button.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[contentView addSubview:button];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow