【问题标题】:Resizing a UIButton programmatically by maintaining a margin通过保持边距以编程方式调整 UIButton 的大小
【发布时间】:2011-01-02 09:50:03
【问题描述】:

我正在以编程方式将 UIButton 添加到 tableView 页脚。这个按钮的左右边距等于 tableView 边距:

UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

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

我添加 autoresizingMask 是因为我想支持旋转。但是,它不能按我的意愿工作,因为按钮一直向右延伸,如下图所示。

知道如何解决吗?如果我删除 autosizing 属性,那么边距是正确的。

【问题讨论】:

    标签: iphone cocoa-touch uitableview


    【解决方案1】:

    UITableView 调整由- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 返回的视图(及其所有子视图)的大小。要解决您的问题,您需要一个包装器视图来布局您的 UIButton 而不使用自动调整大小。以下是此类UIView 类的示例实现:

    @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
    

    只需在- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 中返回此视图,您的按钮就会正确显示。

    我也有uploaded a sample project,它完全实现了上述解决方案。

    【讨论】:

    • 太棒了,谢谢!我稍后会试试这个并回复你。
    猜你喜欢
    • 2017-03-23
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多