Problemi con autoresizingMask e margini fissi
-
09-10-2019 - |
Domanda
sto cercando di ottenere questo al lavoro con il codice in vista di un ViewController:
, ma non posso farlo funzionare.
Ho provato
-(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];
}
ma la larghezza del pulsante è ancora la larghezza del superview ...
Sono sicuro che c'è una spiegazione semplice.
Grazie a tutti!
Antonio
Soluzione
-initWithFrame:
è l'inizializzatore designato per UIView. Sul lato Mac (NSView) So che le cose strane possono accadere quando si utilizza -init
invece di -initWithFrame:
. Forse questo è il problema?
Altri suggerimenti
Invece di preoccuparsi con la bandiera autoresizingMask
, sovrascrivo layoutSubviews
in UIView
sottoclasse personalizzata:
- (void)loadView { self.view = [ContentView view]; self.view.frame = CGRectMake(0, 0, 30, 100); }
dove ContentView
è definito come:
@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); } }
Prova questo codice.
- (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];
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow