简体   繁体   中英

Dynamic label text with space between lines + custom width of line

I am trying to achieve something similar to 理想的结果

currently, my posts are collected from a database and are put into a label, as such.

当前标签

I have tried using attributed strings and changing the background colors of the text - however, I would like to achieve what is in the picture with spaces between the lines and custom width for each line of text. How would I achieve this effect with dynamic text?

Step 1) Break a string up into lines. You have to know the width of your target view. view.bounds.width will do.

See link Question to show you how to break up the text into lines. Pay attention to the question not the answer although that will be part of the answer on the next step.

Step 2) Ditch UILabel. Use UITextView at the very least. Apple changed UILabel to pull down orphan words so even if you get the lines right, a UILabel may not give you the look of what you are doing since it could pull a word down. Use a UITextView and disable scroll, editing disabled, and possibly selection disabled. That will give you intrinsic size to lay it out like a UILabel.

Step 3) Use attributed String to add the backgroundColor/highlighting you seek or use multiple UITextViews(possibly with a UIStackView) or CATextLayers with manual layout to divide your lines up in their own view or layer with the spacing you desire and just use the backgroundColor property. That's up to you. I don't know what you are after.

Sorry I did not show you exactly and only pieced together snippets but this is how you do it. Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM