我正在尝试将其与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];
}

但是按钮的宽度仍然是Supperiew的宽度...

我敢肯定有一个简单的解释。

谢谢大家!

安东尼奥

有帮助吗?

解决方案

-initWithFrame: 是Uiview的指定初始化器。在Mac侧(nsview),我知道使用时可能会发生奇怪的事情 -init 代替 -initWithFrame:. 。也许这是问题?

其他提示

而不是打扰 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);
}

}

尝试此代码。

- (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];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top