Reputation: 211
I am facing a problem with UIButton
. I want to make that type of UIButton
explained in the title of my question. I searched and found many codes but in obj c. Can somebody tell me how to do it in Swift ??..I'm using that button to show the userNames so that if any user will tap on it , segue will happen to show that user's profile. So userNames
can be of any length.. How can i make that type of UIButton
? Thanks for your time
Upvotes: 1
Views: 1035
Reputation: 965
I'm pretty sure all you have to do is set an height constraint and any text will automatically work itself to from a box according to the length of the text. Just make sure that you have enough space on the device that you are running the application on for the text to grow. Also make sure that there are no horizontal constraints that may affect the UIButton.
Upvotes: 0
Reputation: 141
Giving X and Y constraints alone may not help you, it may lead to constraint issue and it doesn't help you change the width of button dynamically. Calculate length of string and change the width of the button programatically. Here Width of the button should be proportional to the length of string.
For example consider string "Hello", here length of the string is 5 characters. Let us assume the width of button which can accommodate these 5 characters is 40.
Now let us consider second string "Hello User" whose length is 10 which is greater than previous string. Now you can use maths to calculate Button's Width.. If button of width 40 can accommodate 5 characters then calculate the width that can accommodate 10 characters. Take width constraint outlet and assign value to it according to string length
Ex: self.string_Btn_Width.constant = (10*40)/5;
I tried this way, as it has nothing to do with programming language this may help you in swift too.
Upvotes: 3
Reputation: 1680
You can try size to fit content
option from the Editor
menu.
Upvotes: 0
Reputation: 7373
If you use auto layout and set the x and y position but not a width and height then it will adopt the size from the text
Upvotes: 3