ios - UIButton 根据标题调整 View 高度 (Swift)

标签 ios swift uiview uibutton

我试图弄清楚如何调整 UIButton 框架的高度,以便它在给定宽度下匹配其 TitleLabel 内容的高度。我目前正在 viewDidAppear 执行此操作。

我尝试通过 NSLayoutConstraint 执行此操作,如下所示:

let attributeString = NSAttributedString(string: button.titleForState(.Normal)!)
let rect = attributeString.boundingRectWithSize(CGSizeMake(self.view.frame.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)

var heightConstraint = NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: button, attribute: .Height, multiplier: 1.0, constant: rect.height)

并通过直接使用上面计算的rect设置UIButtonframe:

button.frame = CGRectMake(0, 0, self.view.frame.width, rect.height)

但是,我无法影响按钮 View 的高度。我偶然能够更改高度的唯一方法是摆弄 NSLayoutConstraintmultiplier 属性,但它会不可预测地更改高度。

有人知道怎么做吗?

编辑

我应该补充一点,文本已通过 NSLineBreakMode.ByWordWrapping 成功换行。这是我的完整按钮构造:

let button = UIButton.buttonWithType(.System) as UIButton
button.setTitle(title, forState: .Normal)
button.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
button.titleLabel?.textAlignment = NSTextAlignment.Center
button.setTranslatesAutoresizingMaskIntoConstraints(false)

问题截图如下: http://i.imgur.com/dEJVRxc.png

最佳答案

我找不到任何好的“自动”方式来执行此操作。对我有用的方法是重写 setTitle:forState: 在 UIButton 子类中,并计算那里用于调整高度约束的文本大小。该按钮有一个高度约束(使用 IBOutlet heightCon),还有一个在 IB 中设置的宽度约束(如果您不使用 IB,您可以在代码中添加这些)

override func setTitle(title: String?, forState state: UIControlState) {
        super.setTitle(title, forState: state)
        let attributeString = NSAttributedString(string: currentTitle!, attributes: [NSFontAttributeName: titleLabel!.font])
        let rect = attributeString.boundingRectWithSize(CGSizeMake(self.frame.width, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil)
        heightCon.constant = rect.size.height + titleEdgeInsets.top + titleEdgeInsets.bottom
    }

关于ios - UIButton 根据标题调整 View 高度 (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490878/

相关文章:

iphone - 需要 iOS 数据库云设计技巧

ios - 如何检查 WKWebView URLAuthenticationChallenge 是否失败或成功?

ios - 自定义栏按钮项目图像框架太宽

swift - 导入与Apple Framework同名的pod Framework

ios - 以编程方式创建 UINavigationBar

ios - Swift UIPageViewController 和 UIActivityIndi​​catorView

macos - 如何在 swift (OSX) 中从函数到结构化变量传递多重返回

ios - 在新的 ViewController 上显示用户的帖子

ios - 如何从父 View 中删除 uiview?

objective-c - 使用 Core Graphics 绘图在 Retina 显示屏上看起来很笨重