【问题标题】:How to increase UIButton height according to its title text?如何根据标题文本增加 UIButton 高度?
【发布时间】:2013-06-14 07:02:40
【问题描述】:

我需要根据标题增加UIButton 的高度。

演示问题的图片如下

【问题讨论】:

标签: iphone ios uibutton cgsize


【解决方案1】:

正如你所说的动态高度,这是经过全面测试的

myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.titleLabel.numberOfLines=0;
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
NSString *titleOfButton=@"this is the very launch soon title here u can pass as long as big string";
[myButton setTitle:titleOfButton forState:UIControlStateNormal];
CGSize constraint1=CGSizeMake(150.0f, 5000.0f);
CGSize size1=[titleOfButton sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
[myButton setFrame:CGRectMake(10,50,150, size1.height+20)];
[self.view addSubview:myButton];

【讨论】:

  • @downvoter-你能解释一下拒绝这个答案的原因吗
  • sizeWithFont 现在已弃用。替换为NSDictionary *attributes =@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:15]}; CGSize size1 = [firstTitle sizeWithAttributes:attributes];
  • 有Autolayout但没有按钮框怎么办?
  • @Kampai- 在这种情况下,不要给按钮设置高度限制。
【解决方案2】:

使用此代码获取帮助

UIFont font = myButton.titleLabel.font;
CGSize textsize = [myButton.titleLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(myButton.frame.size.width,999) lineBreakMode:UILineBreakModeTailTruncation]; 

[myButton setFrame:CGRectMake(myButton.frame.origin.x,myButton.frame.origin.y,myButton.frame.size.width, textsize.height)];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多