UITextView를 사용하여 다음과 같은 효과를 얻으려고합니다.

기본적으로 텍스트 사이에 이미지를 삽입하고 싶습니다. 이미지는 단순히 한 줄의 공간 만 차지할 수 있으므로 줄 바꿈이 필요하지 않습니다.
하위보기에 UIView를 추가하려고했습니다.
UIView *pictureView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
[pictureView setBackgroundColor:[UIColor redColor]];
[self.textView addSubview:pictureView];그러나 그것은 텍스트 위에 떠 있고 그것을 덮는 것처럼 보입니다.
나는 이것을 구현하는 한 가지 방법으로 보이는 제외 경로 에 대해 약간 읽었습니다 . 그러나 이미지의 위치를 절대적으로 지정하고 싶지는 않습니다. 대신 텍스트와 함께 흐릅니다 ( <span>HTML에서 작동 하는 방식과 유사 ).
답변
속성이있는 문자열을 사용하고 이미지를의 인스턴스로 추가해야합니다 NSTextAttachment.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"like after"];
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = [UIImage imageNamed:@"whatever.png"];
NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[attributedString replaceCharactersInRange:NSMakeRange(4, 1) withAttributedString:attrStringWithImage];답변
@bilobatum의 코드는 필요한 사람들을 위해 Swift로 변환되었습니다.
let attributedString = NSMutableAttributedString(string: "like after")
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage(named: "whatever.png")
let attrStringWithImage = NSAttributedString(attachment: textAttachment)
attributedString.replaceCharacters(in: NSMakeRange(4, 1), with: attrStringWithImage)답변
NSAttributedString 및 NSTextAttachment를 사용해 볼 수 있습니다. 이미지 크기를 조정하기 위해 NSTextAttachment를 사용자 지정하는 방법에 대한 자세한 내용은 다음 링크를 참조하십시오.
http://ossh.com.au/design-and-technology/software-development/implementing-rich-text-with-images-on-os-x-and-ios/
내 예에서는 너비에 맞게 이미지 크기를 조정합니다. 귀하의 경우에는 선 높이와 일치하도록 이미지 크기를 조정할 수 있습니다.
답변
@bilobatum의 답변을 확장하고 다른 질문 에서이 범주 를 사용 합니다 . 나는 이것을 요리했다 :
용법:
UILabel *labelWithImage = [UILabel new];
labelWithImage.text = @"Tap [new-button] to make a new thing!";
NSAttributedString *stringWithImage = [labelWithImage.attributedText attributedStringByReplacingOccurancesOfString:@"[new-button]" withImage:[UIImage imageNamed:@"MyNewThingButtonImage"] scale:0];
labelWithImage.attributedText = stringWithImage;이행:
@interface NSMutableAttributedString (InlineImage)
- (void)replaceCharactersInRange:(NSRange)range withInlineImage:(UIImage *)inlineImage scale:(CGFloat)inlineImageScale;
@end
@interface NSAttributedString (InlineImages)
- (NSAttributedString *)attributedStringByReplacingOccurancesOfString:(NSString *)string withInlineImage:(UIImage *)inlineImage scale:(CGFloat)inlineImageScale;
@end.
@implementation NSMutableAttributedString (InlineImages)
- (void)replaceCharactersInRange:(NSRange)range withInlineImage:(UIImage *)inlineImage scale:(CGFloat)inlineImageScale {
    if (floorf(inlineImageScale) == 0)
        inlineImageScale = 1.0f;
    // Create resized, tinted image matching font size and (text) color
    UIImage *imageMatchingFont = [inlineImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    {
        // Font size
        NSDictionary *attributesForRange = [self attributesAtIndex:range.location effectiveRange:nil];
        UIFont *fontForRange = [attributesForRange valueForKey:NSFontAttributeName];
        CGSize imageSizeMatchingFontSize = CGSizeMake(inlineImage.size.width * (fontForRange.capHeight / inlineImage.size.height), fontForRange.capHeight);
        // Some scaling for prettiness
        CGFloat defaultScale = 1.4f;
        imageSizeMatchingFontSize = CGSizeMake(imageSizeMatchingFontSize.width * defaultScale,     imageSizeMatchingFontSize.height * defaultScale);
        imageSizeMatchingFontSize = CGSizeMake(imageSizeMatchingFontSize.width * inlineImageScale, imageSizeMatchingFontSize.height * inlineImageScale);
        imageSizeMatchingFontSize = CGSizeMake(ceilf(imageSizeMatchingFontSize.width), ceilf(imageSizeMatchingFontSize.height));
        // Text color
        UIColor *textColorForRange = [attributesForRange valueForKey:NSForegroundColorAttributeName];
        // Make the matching image
        UIGraphicsBeginImageContextWithOptions(imageSizeMatchingFontSize, NO, 0.0f);
        [textColorForRange set];
        [inlineImage drawInRect:CGRectMake(0 , 0, imageSizeMatchingFontSize.width, imageSizeMatchingFontSize.height)];
        imageMatchingFont = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    // Text attachment with image
    NSTextAttachment *textAttachment = [NSTextAttachment new];
    textAttachment.image = imageMatchingFont;
    NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:textAttachment];
    [self replaceCharactersInRange:range withAttributedString:imageString];
}
@end
@implementation NSAttributedString (InlineImages)
- (NSAttributedString *)attributedStringByReplacingOccurancesOfString:(NSString *)string withInlineImage:(UIImage *)inlineImage scale:(CGFloat)inlineImageScale {
    NSMutableAttributedString *attributedStringWithImages = [self mutableCopy];
    [attributedStringWithImages.string enumerateOccurancesOfString:string usingBlock:^(NSRange substringRange, BOOL *stop) {
        [attributedStringWithImages replaceCharactersInRange:substringRange withInlineImage:inlineImage scale:inlineImageScale];
    }];
    return [attributedStringWithImages copy];
}
@end답변
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "qrcode")
let iconString = NSAttributedString(attachment: attachment)
let firstString = NSMutableAttributedString(string: "scan the ")
let secondString = NSAttributedString(string: "QR code received on your phone.")
firstString.append(iconString)
firstString.append(secondString)
self.textLabel.attributedText = firstString답변

