user5899631
user5899631

Reputation:

How to align UIButton to the left with UILabel on the right. Like instagram's comments

I am trying to have the username on the right and then a UIlabel with some text to the left of the button.

Here is an example of what I am after: enter image description here

I am just not sure how I can get the constraints to do that, especially the part where the UILabel text continues on the next line below the button...?!

If anyone has any ideas, any help is appreciated!

Regards.

Upvotes: 1

Views: 324

Answers (2)

smozgur
smozgur

Reputation: 1812

Please see the sample I created on my UIButton inside UITextView idea: https://github.com/smozgur/UIButton-inside-UITextView I am still playing with it but it results fine so far.

Upvotes: 2

toddg
toddg

Reputation: 2906

I think the best approach would be to do it all with one label. You could set the text styling using an attributed string (code below). Then create a UIButton that is laid on top of the label (the size of the UIButton can be adjusted based on length of username).

This is the approach I used when creating a disclaimer label on a signup screen as shown below

enter image description here

Here's the code to create the attributed string:

let disclaimerAttributedString = NSMutableAttributedString(string: disclaimerLabel.text!, attributes: [NSKernAttributeName: -0.4])
disclaimerAttributedString.addAttributes([NSForegroundColorAttributeName: UIColor.whiteColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: NSMakeRange(38, 12))
disclaimerAttributedString.addAttributes([NSForegroundColorAttributeName: UIColor.whiteColor(), NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: NSMakeRange(55, 14))
disclaimerLabel.attributedText = disclaimerAttributedString

My situation is slightly different because I am applying it to static text. For you, you can either create the button in code based on the length of the username or you may just be able to approximate it by pinning the button to the top left of the UILabel.

You could figure out the length of the attributed string that the username would occupy by using the String extension in this SO answer

Upvotes: 1

Related Questions