Sathish Kumar
Sathish Kumar

Reputation: 87

How to set button width based on text for dynamically created button in swift 3?

I created the dynamic buttons. I need to change the width of button based on tittle label text. Here is my code.

       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()
    }

Upvotes: 1

Views: 6558

Answers (2)

Naren
Naren

Reputation: 1702

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
}

Upvotes: 2

Rakshith Nandish
Rakshith Nandish

Reputation: 639

Try this

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
}

This will give you the frame of the label, you can set the height of your button from that.

Upvotes: 2

Related Questions