我正在尝试使用UITextFieldNSTextAttachment中显示图像,但是我希望图像和文本之间有一些水平空间。但是,当按如下方式将NSKernAttributeName属性添加到属性字符串时,它将附件的高度重置为与周围文本相同的高度。

var str = NSMutableAttributedString(attributedString: NSAttributedString(attachment: imageAttachment))
str.addAttribute(NSKernAttributeName, value: 10, range: NSRange(location: 0,length: 1))

还有另一种方法可以在图像和文本之间添加水平空间吗?

最佳答案

最直接的方法是在字符串开始处设置一些空间:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
[attachment setImage:[UIImage imageNamed:@"dest_poi_content_quotation"]];
NSString *reviewText = [NSString stringWithFormat:@"  %@", review.text];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:reviewText];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:attachment];
[attributedString insertAttributedString:attrStringWithImage atIndex:0];
[self.lblComment setAttributedText:attributedString];

10-08 12:30