Pregunta

Estoy tratando de conseguir esto para trabajar con código en la vista de un ViewController:

text alt

pero no puedo conseguir que funcione.

He intentado

-(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];
}

pero la anchura del botón sigue siendo la anchura de la supervista ...

Estoy seguro de que hay una explicación fácil.

Gracias a todos!

Antonio

¿Fue útil?

Solución

-initWithFrame: es el inicializador designado para UIView. Por el lado de Mac (NSView) Sé que las cosas extrañas pueden suceder cuando se utiliza en lugar de -init -initWithFrame:. Tal vez este es el problema?

Otros consejos

En lugar de molestarse con la bandera autoresizingMask, que anula layoutSubviews en la subclase UIView personalizado:

- (void)loadView {
    self.view = [ContentView view];
    self.view.frame = CGRectMake(0, 0, 30, 100);
}

donde ContentView se define como:

@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);
}

}

Trate de este código.

- (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];
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top