如何使用iOS7中的自动布局使按钮垂直增长?

时间:2013-12-03 19:54:30

标签: ios cocoa-touch button layout autolayout

使用IB和自动布局我希望有一个按钮,当标题很长时,它会垂直增大。

我已经为按钮添加了top,leading和trailing约束以及Word换行的换行符。然后我在viewDidLoad中指定一个长标题。但结果按钮不适合内容。我在这里缺少什么?

IB

Simulator

Button

Constraints

试图克服缺乏自动更新高度的问题:

CGFloat width = 280;
NSAttributedString *attributedText =
[[NSAttributedString alloc]
 initWithString:self.button.titleLabel.text
 attributes:@
 {NSFontAttributeName: self.button.titleLabel.font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
CGSize size = rect.size;
CGRect buttonRect = self.button.frame;
buttonRect.size.height = size.height;
[self.button setFrame: buttonRect];

但是按钮的框架没有更新.....

根据rdelmar提供的优秀解决方案,我得到了以下结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

如果你想要图像上的标题(而不是旁边),你需要使用backgroundImage:forState:。据我试验一下,你无法通过自动方式使用标题扩展图像。如果没有图像,则这些约束可以使标题垂直展开。

编辑后:我从未找到任何好的自动方式来执行此操作,但您可以通过计算字符串的高度并相应地调整按钮的高度来实现。我发现最好的方法是在IB中为按钮提供宽度和高度约束 - 这将使您的背景图像拉伸或缩小以适合该帧。我创建了一个UIButton子类(更改了IB中按钮的类),并将此代码放入其中:

@interface RDButton ()
@property (strong,nonatomic) NSLayoutConstraint *hCon;
@property (strong,nonatomic) NSLayoutConstraint *wCon;
@property (nonatomic) CGFloat startingHeight;
@end

@implementation RDButton

-(id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        for (NSLayoutConstraint *con in self.constraints) {
            if (con.firstAttribute == NSLayoutAttributeHeight) {
                self.hCon = con;
                self.startingHeight = con.constant;
            }else if (con.firstAttribute == NSLayoutAttributeWidth){
                self.wCon = con;
            }
        }
    }
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    return self;
}

-(void)setTitle:(NSString *)title forState:(UIControlState)state {
    [super setTitle:title forState:state];
    NSStringDrawingContext *ctx = [NSStringDrawingContext new];
    CGSize s = [title boundingRectWithSize:CGSizeMake(self.wCon.constant, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleLabel.font} context:ctx].size;
    self.hCon.constant = fmax (s.height, self.startingHeight - 5) + 5; // the +5 gives about the same padding as the original button.
}

在我设置新标题的视图控制器中,我有:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.button setTitle:@"A long long long Title" forState:UIControlStateNormal];
    UIImage *img = [UIImage imageNamed:@"pic.jpg"];
    [self.button setBackgroundImage:img forState:UIControlStateNormal];
}