In my app i need to display the text content along with image in UILabel like this
but i am only able to display text along with image like this text string in UILabel is starting from the bottom of the image. But i need to start the text from the top.
I am using the following code please help me to display the image with text in proper format.
let topDesc = responseDict?["description_top"]?.string ?? ""
// Create Attachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"no-image")
// Set bound to reposition
let imageOffsetY: CGFloat = 0
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: 130, height: 92)
// Create string with attachment
let attachmentString = NSAttributedString(attachment: imageAttachment)
// Initialize mutable string
let completeText = NSMutableAttributedString(string: "")
// Add image to mutable string
completeText.append(attachmentString)
// Add your text to mutable string
let textAfterIcon = NSAttributedString(string: topDesc)
completeText.append(textAfterIcon)
self.topContentLbl.textAlignment = .center
self.topContentLbl.attributedText = completeText
2
Answers
This is an alternative way to do it, declare your objects and set constraints:
This is the result:
You can do this by using a
UITextView
and.exclusionPaths
.Here, the yellow-background text view is 353-points wide and I define a 116×80 rectangular
UIBezierPath
:By setting
.isScrollEnabled = false
on the text view, it will size its own height based on the text.Now, all we need to do is add the rounded-rect view and the image view on top of it.
To get your exact layout – using a single string of text – will be a little difficult.
As you see in the above image, the text flows around the exclusion path, but the image you posted looks more like this:
To get that, I added two line-feeds in the string:
However, unless you’re writing the copy to match the available space, it might look like this:
or this:
If you need the paragraph break as shown in your image, your best option would probably be to embed a special character (or, for example, the double line-break) and split the string at run-time to fill two labels laid out as desired.
Here’s a quick example showing how to use the
.exclusionPaths
: