Stephen Martyn
Stephen Martyn

Reputation: 1

Resizing UIButton height with code?

I am trying to set a clickable "textonly"-button but right now I'm having problem fixing the height for my button. Before all this I tried having it as an label, but then the touchhandling gets complicated so I decided to just do a button with no frame etc.. So now I need to set the buttonheight to the Text thats inside, any ideas? Heres a code snippet:

 //...
    button.setTitle("Log in", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.layer.borderWidth = 0
    button.frame = CGRect
    button.addTarget(self, action: #selector(LoginFunction), for: .touchUpInside)
    //...

Upvotes: 0

Views: 184

Answers (2)

Alexey Tyurnin
Alexey Tyurnin

Reputation: 326

If you want multiple lines of text in your UIButton you should set yourButton.titleLabel?.numberOfLines = 0 and yourButton.titleLabel?.lineBreakMode = .byWordWrapping. You will get multiline button, which height you can configure as you want. Also you calculate frame of your text you should use

let context = NSStringDrawingContext()
let frame = yourText.boundingRectWithSize(
    CGSize(width: yourButtonWidth, height: 9999),
    options: NSStringDrawingOptions.UsesLineFragmentOrigin,
    attributes: dictionaryOfYourTextAttributes, context: context)

Upvotes: 1

ramacode
ramacode

Reputation: 924

You should still have a frame for the button to be displayed in the UI. It define yours button position and size (including height). Here is an example for button with position (0,0) and size (100,100):

button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)

Maybe what you mean by "frame" is "border". You can achieve borderless button by setting borderWidth to 0, which you already did in your code.

button.layer.borderWidth = 0

If you want to set size for the text you can do:

button.titleLabel?.font = UIFont.systemFont(ofSize: 17)

Upvotes: 0

Related Questions