UIImage in the end of UILabel text

▼魔方 西西 提交于 2019-12-10 15:55:06

问题


how to find coordinate 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.


回答1:


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



回答2:


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.




回答3:


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...




回答4:


sizeWithFont does not take care of the UILabel edges.



来源:https://stackoverflow.com/questions/3607113/uiimage-in-the-end-of-uilabel-text

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