Make label only as wide as it needs to be?

社会主义新天地 提交于 2019-12-25 05:32:30

问题


I have 3 labels next to each other inside a horizontal stack view like this

The first and last label are going to be dynamically filled with a word of variable length, while the middle one is always going to contain the word "with", for example: "Coding with Swift!"

I don't want there to be extra space between each word as it would look strange if the words are short. Is there any way to make the labels only be as wide as they need to be to fit their text? That way it all looks like one label (except I'm making the middle label have smaller text).


回答1:


Add 3 labels inside a UIView instead of stack view. And set constraints as shown in image.




回答2:


How about using autolayout? You could give a horizontal space of 0 between the labels and a constraint of width for the middle one.




回答3:


If u wish to have different fonts for the content in a label you can use NSAttributedString

let boldFontDict:[String: AnyObject] = [NSForegroundColorAttributeName : UIColor.black, NSFontAttributeName: <UI Font>]

let 1stString = NSAttributedString(string: "Hello")      
let 2ndString = NSAttributedString(string: "hii", attributes: boldFOntDict)

let finalAttrStr = NSMutableAttributedString(attributedString: 1stString)

finalAttrStr.append(2ndString)

myLabel.attributedText = finalAttrStr



回答4:


You can take one label instead of taking three label and and set the text on label as

  label.text= firstLabel.text + "with" + lastLabel.text



回答5:


You can use autolayout to fix this problem.



来源:https://stackoverflow.com/questions/42340026/make-label-only-as-wide-as-it-needs-to-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!