开发者

Resizing a UIButton programmatically by maintaining a margin

I'm a开发者_运维问答dding a UIButton to a tableView footer programmatically. This button has a left and right margin that is equal to the tableView margin:

UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

deleteButton.frame = CGRectMake(10, 60, 300, 34);
deleteButton.autoresizingMask = UIViewAutoresizingFlexibleWidth

I'm adding autoresizingMask because I want to support rotation. However, it does not work as I want, as the button stretches all the way down to the right, as shown by the image below.

Any idea how to fix it? If I remove the autosizing property then the margin is correct.

Resizing a UIButton programmatically by maintaining a margin


UITableView resizes the view (and all its subviews) returned by - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section. To fix your issue, you need a wrapper view that layouts your UIButton without using autoresizing. Here’s an example implementation of such an UIView class:

@interface ButtonWrapperView : UIView {
    UIButton *_button;
}

@property (nonatomic, readonly) UIButton *button;

@end


@implementation ButtonWrapperView

@synthesize button = _button;

- (id)init
{
    if ((self = [super initWithFrame:CGRectZero])) {
        _button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        [self addSubview:_button];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    // Layout button
    _button.frame = CGRectMake(10.0f, 0.0f, self.bounds.size.width - 20.0f, self.bounds.size.height);
}

- (void)dealloc
{
    [_button release];
    [super dealloc];
}

@end

Simply return this view in - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section and your button should be displayed properly.

I’ve also uploaded a sample project which completely implements the above solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜