通过保持边距以编程方式调整UIButton的大小 [英] Resizing a UIButton programmatically by maintaining a margin
问题描述
我正在以编程方式将UIButton添加到tableView页脚中。此按钮的左右边距等于tableView的边距:
I'm adding 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
我要添加autoresizingMask,因为我想支持旋转。但是,它不能按我想要的方式工作,因为该按钮一直向下延伸到右侧,如下图所示。
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.
推荐答案
UITableView
调整视图的大小(以及所有其子视图)由-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
返回。要解决您的问题,您需要一个包装视图,该视图在不使用自动调整大小的情况下布置 UIButton
的布局。这是这样的 UIView
类的示例实现:
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
在-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)部分
,您的按钮应正确显示。
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.
这篇关于通过保持边距以编程方式调整UIButton的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!