UIImage in the end of UILabel text
how to find coordin开发者_开发百科ate of the last character in UILabel if we have more then 1 line of text in it? I would like to add an image in the end of the text.
I think you are looking for NSTextAttachment
// create an NSMutableAttributedString
let fullString = NSMutableAttributedString(string: "Your text")
// create our NSTextAttachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "icon")
// wrap the attachment in its own attributed string so we can append it
let imageString = NSAttributedString(attachment: imageAttachment)
// add the NSTextAttachment wrapper to our full string, then add some more text.
fullString.append(imageString)
// draw the result in a label
yourLabel.attributedText = fullString
Not exactly, but what you can do is find out how high your label will have to be to accommodate your text using -[NSString sizeWithFont:constrainedToSize:lineBreakMode:]
and once you have the height, you can work out from there, knowing the right edge of the label, and the height, how to position your image as a subview of the container view.
I.e., you may want to add it immediately to the right of the label at the bottom of the label, in which case, add it as a subview where its x axis is the right edge of the label (label's x axis + width), and where the imageview has its y axis set to the y axis of the label + the label's height, minus the size of your font should put it in the right spot, however, you may want to instead of using the label's font height property in the last calculation, to use the height of the imageview instead so it is flush with the bottom of the label and the bottom of the image view... hard to say really without seeing a mockup.
That should give you enough to go on anyway.
You can use this code to get the height of your text as per the width and content.
Try this code and inser the image at the given height.
-(float)getHeightByWidth:(NSString*)myString:(UIFont*)mySize:(int)myWidth
{
CGSize boundingSize = CGSizeMake(myWidth, CGFLOAT_MAX);
CGSize requiredSize = [myString sizeWithFont:mySize constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
return requiredSize.height;
}
hAPPY cODING...
sizeWithFont
does not take care of the UILabel
edges.
精彩评论