如何创建和使用自动布局从code。与多行添加标签的UIButton? [英] How to create and add UIButton with multiline label from code using autolayout?

查看:191
本文介绍了如何创建和使用自动布局从code。与多行添加标签的UIButton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有很多环节如何大小的标签,但有一个缺乏信息如何根据其标签的大小调整的UIButton的。目前,我有屏幕视图与自动布局(所有的制度约束是从IB加)一套,一切工作正常,但需要在屏幕的底部添加动态内容。我需要创建和添加按钮的随机数随机长度标题。所以,这里的code片段用于创建和添加的按钮:

There's are a lot of links how to size a label, however there's a lack of info how to resize UIButton according to its label size. Currently, I have screen view set with autolayout (all the system constraints are added from IB) and everything works fine, but need to add dynamic content at the bottom of the screen. I need to create and add random number of buttons with random length titles. So, here's code fragment for creating and adding the buttons:

// Loop
  UIButton *myButton = [UIButton new];

  UIButton.frame = CGRectMake(0, previousButtonOriginY, self.view.bounds.size.width, 20);
  myButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
  myButton.titleLabel.textAlignment = NSTextAlignmentLeft;
  myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
  [myButton setTitle:@"very long title..." forState:UIControlStateNormal];
  myButton.titleLabel.numberOfLines = 0;

  [self.footerView addSubview:myButton];

问题是按钮的帧的高度保持20像素,但标签字符串显示在三线等与其他按钮名称重叠。如果我添加[myButton的sizeToFit]按钮,然后宽度调整大小以适合所有文本成一行等称号超越了屏幕。

The problem is the frame height of the button stays 20px but the label string is shown on three lines and so overlaps with the other button title. If I add [myButton sizeToFit] then button width is resized to fit all the text into one line and so the title goes beyond the screen.

如果我添加[myButton的sizeThatFits:CGSizeMake(320,100)],然后调整是不工作的。我知道sizeToFit不应该在所有调用,因为它不是自动布局的一部分,但需要在该按钮的建议是多么容易做出适合其标签屏幕320的宽度。

If I add [myButton sizeThatFits:CGSizeMake(320, 100)] then resize is not working at all. I know sizeToFit should not be called at all because it's not the part of autolayout, however need suggestions on that how easily to make button fit its label to screen 320 width.

我觉得我需要从code添加系统约束,但还没有做之前,所以不知道应该怎么样子。我可能需要一吨的限制是从$​​ C $ C,为了得到这个简单的事情工作补充说:)

I feel I need to add system constraints from code, but haven't done that before, so not sure how it should look like. I probably need a ton of constraints to be added from code in order to get this simple thing working :)

推荐答案

对于这种你需要创建的UIButton的子类定制的。在子类中,您可以添加自定义标签,这有利于您的需求。您还可以覆盖到的setTitle:forState方法来自动更新您的自定义标签

For this kind of customizations you'll need to create a subclass of UIButton. In the subclass you can add a customized label which benefits your needs. You can also override to setTitle:forState method to automatically update your customized label.

这篇关于如何创建和使用自动布局从code。与多行添加标签的UIButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆