autoresizingMask和固定边距有问题

时间:2010-11-12 11:00:46

标签: iphone ios autoresize autoresizingmask

我正在尝试使用ViewController视图中的代码:

alt text

但我无法让它发挥作用。

我试过

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

但按钮的宽度仍然是超视图的宽度...

我确信这是一个简单的解释。

谢谢大家!

安东尼奥

3 个答案:

答案 0 :(得分:0)

-initWithFrame:是UIView的指定初始化程序。在Mac端(NSView),我知道在使用-init而不是-initWithFrame:时会发生奇怪的事情。也许这就是问题?

答案 1 :(得分:0)

我没有使用autoresizingMask标记,而是覆盖自定义layoutSubviews子类中的UIView

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

其中ContentView定义为:


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

}

答案 2 :(得分:0)

试试这段代码。

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