如何根据swift 3中动态创建按钮的文本设置按钮宽度?

时间:2017-04-15 06:04:03

标签: swift dynamic uibutton width

我创建了动态按钮。我需要根据tittle标签文本更改按钮的宽度。这是我的代码。

       for i in 0..<holdingSize { 
       let button = UIButton(type: .custom)

        if i == 0 {
            frame = CGRect(x: 10, y: 5, width: 100, height: 30)
        }else{
            buttonY = buttonY + 110
            frame = CGRect(x: buttonY, y: 5, width: 100, height: 30)
        }
        button.setTitle("\(arrayOfHoldings[i])", for: UIControlState.normal) // We are going to use the item name as the Button Title here.
        button.titleLabel?.text = "\(arrayOfHoldings[i])"
        button.titleLabel?.font = UIFont(name: (button.titleLabel?.font.fontName)!, size: 15)
        button.setTitleColor(Colors.green, for: .normal)
        button.sizeToFit()
    }

2 个答案:

答案 0 :(得分:2)

试试这个

func labelSizeWithString(text: String,fontSize: CGFloat, maxWidth : CGFloat,numberOfLines: Int) -> CGRect{

    let font = UIFont.systemFontOfSize(fontSize)//(name: "HelveticaNeue", size: fontSize)!
    let label = UILabel(frame: CGRectMake(0, 0, maxWidth, CGFloat.max))
    label.numberOfLines = numberOfLines
    label.font = font
    label.text = text

    label.sizeToFit()

    return label.frame
}

这将为您提供标签的框架,您可以从中设置按钮的高度。

答案 1 :(得分:2)

FOR SWIFT 3.0

func labelSize(for text: String,fontSize: CGFloat, maxWidth : CGFloat,numberOfLines: Int) -> CGRect{

    let font = UIFont.systemFont(ofSize: fontSize)//(name: "HelveticaNeue", size: fontSize)!
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: maxWidth, height: CGFloat.leastNonzeroMagnitude))
    label.numberOfLines = numberOfLines
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame
}