UFO ET IT

iPhone-동시에 여러 글꼴이있는 텍스트를 포함하는 UILabel

ufoet 2020. 11. 22. 20:57
반응형

iPhone-동시에 여러 글꼴이있는 텍스트를 포함하는 UILabel


UILabel (또는 비슷한 것)을 사용하여 다음과 같이 표시하는 방법을 찾고 있습니다.

Tom : 메시지가 있습니다.

예를 들어 페이스 북 앱에서 "당신의 생각은 무엇입니까?"를 표시하는 것과 같습니다. 메시지. 누구든지 이것에 접근하는 방법에 대한 제안이 있습니까?


원하는대로 각각 다른 형식 (글꼴 / 색상 / 기타)을 가진 두 개의 UILabel IBOutlet을 사용하십시오. 첫 번째 텍스트가 끝나는 위치를 기준으로 두 번째 것을 첫 번째 위로 이동하십시오. sizeWithFont : forWidth : lineBreakMode를 통해 얻을 수 있습니다.

또는 UILabel을 하위 클래스로 만들고 drawRect에서 직접 텍스트를 그릴 수 있습니다. 이 방법을 사용하는 경우 인스턴스 변수를 추가하여 한 형식으로 그릴 문자열의 양을 알려주고 나머지는 다른 형식으로 그립니다.

업데이트 : 아래 @Akshay의 응답을 참조하십시오. iOS6부터 UILabel은 NSMutableAttributedString을 포함 할 수 있습니다. 내가 이것을 썼을 때 이것은 사용할 수 없었습니다.


NSMutableAttributedString을 사용하여 Label에 다른 / 다중 글꼴 및 기타 속성을 설정하는 방법이 있습니다. Foll은 내 코드입니다.

 UIFont *arialFont = [UIFont fontWithName:@"arial" size:18.0];
 NSDictionary *arialDict = [NSDictionary dictionaryWithObject: arialFont forKey:NSFontAttributeName];    
 NSMutableAttributedString *aAttrString = [[NSMutableAttributedString alloc] initWithString:title attributes: arialDict];

 UIFont *VerdanaFont = [UIFont fontWithName:@"verdana" size:12.0];
 NSDictionary *verdanaDict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName];
 NSMutableAttributedString *vAttrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:verdanaDict];    
 [vAttrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))];

 [aAttrString appendAttributedString:vAttrString];


 lblText.attributedText = aAttrString;

lblText는 파일 소유자로서의 출력 인 UILabel입니다. 원하는만큼 NSMutableAttributedString을 계속 추가 할 수 있습니다.

또한 내 프로젝트에 verdana 및 arial 글꼴을 추가하고 동일한 plist를 추가했습니다.


답변이 늦어서 죄송합니다. 아래 코드는 나를 위해 잘 작동합니다. 누군가에게 도움이 될 수 있도록 이것을 게시하고 있습니다.

    UIFont *font1 = [UIFont fontWithName:kMyriadProSemiBold size:15];
NSDictionary *arialDict = [NSDictionary dictionaryWithObject: font1 forKey:NSFontAttributeName];
NSMutableAttributedString *aAttrString1 = [[NSMutableAttributedString alloc] initWithString:@"My" attributes: arialDict];

UIFont *font2 = [UIFont fontWithName:kMyriadProRegular size:15];
NSDictionary *arialDict2 = [NSDictionary dictionaryWithObject: font2 forKey:NSFontAttributeName];
NSMutableAttributedString *aAttrString2 = [[NSMutableAttributedString alloc] initWithString:@"Profile" attributes: arialDict2];


[aAttrString1 appendAttributedString:aAttrString2];
myProfileLabel.attributedText = aAttrString1;

여기에 이미지 설명 입력

My는 세미 볼드이고 프로필은 규칙적입니다. MyRiad 글꼴을 사용했습니다. 감사


업데이트 : iOS 6 이상인 경우 UILabel.attributedText를 사용하십시오.

유사한 기능을 지원하기 위해이 기본 UIView 하위 클래스를 만들었습니다.

지원 하지 않는 항목의 목록은 수행하는 것 보다 길지만 기본적으로 UILabels 을 관리하고 원하는대로 각각 형식을 지정할 수 있습니다. 이를 통해 예를 들어 줄 중간에 다른 색상의 텍스트를 삽입하고 무거운 UIWebView를 사용하지 않아도됩니다.

인터페이스 빌더를 사용하여 인터페이스에 UIView 개체를 배치하고 IB의 개체 유형을 MultipartLabel로 설정하여 이러한 개체를 만듭니다. 그런 다음 코드에서 필요에 따라 updateNumberOfLabels 및 다양한 setText 선택기를 호출합니다.

//  MultipartLabel.m
//  MultiLabelLabel
//
//  Created by Jason Miller on 10/7/09.
//  Copyright 2009 Jason Miller. All rights reserved.
//

#import "MultipartLabel.h"

@interface MultipartLabel (Private)
- (void)updateLayout;
@end

@implementation MultipartLabel

@synthesize containerView;
@synthesize labels;

-(void)updateNumberOfLabels:(int)numLabels;
{
 [containerView removeFromSuperview];
 self.containerView = nil;

 self.containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)] autorelease];
 [self addSubview:self.containerView];
 self.labels = [NSMutableArray array];

 while (numLabels-- > 0) {
  UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];
  [self.containerView addSubview:label];
  [self.labels addObject:label];
  [label release];
 }

 [self updateLayout];
}

-(void)setText:(NSString *)text forLabel:(int)labelNum;
{
 if( [self.labels count] > labelNum && labelNum >= 0 )
 {
  UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
  thisLabel.text = text;
 }

 [self updateLayout];
}

-(void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum;
{
 if( [self.labels count] > labelNum && labelNum >= 0 )
 {
  UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
  thisLabel.text = text;
  thisLabel.font = font;
 }

 [self updateLayout];
}

-(void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum;
{
 if( [self.labels count] > labelNum && labelNum >= 0 )
 {
  UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
  thisLabel.text = text;
  thisLabel.textColor = color;
 }

 [self updateLayout];
}

-(void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum;
{
 if( [self.labels count] > labelNum && labelNum >= 0 )
 {
  UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
  thisLabel.text = text;
  thisLabel.font = font;
  thisLabel.textColor = color;
 }

 [self updateLayout];
}

- (void)updateLayout {

 int thisX = 0;

 // TODO when it is time to support different sized fonts, need to adjust each y value to line up baselines

 for (UILabel * thisLabel in self.labels) {
  CGSize size = [thisLabel.text sizeWithFont:thisLabel.font
         constrainedToSize:CGSizeMake(9999, 9999)
          lineBreakMode:thisLabel.lineBreakMode];
  CGRect thisFrame = CGRectMake( thisX, 0, size.width, size.height );
  thisLabel.frame = thisFrame;

  thisX += size.width;
 }
}


- (void)dealloc {
 [labels release];
 labels = nil;

 [containerView release];
 containerView = nil;

    [super dealloc];
}


@end

Swift 2.0에서는 다음과 같이 수행 할 수 있습니다.

//Defining fonts of size and type
let firstfont:UIFont = UIFont(name: "Helvetica Neue", size: 17)!
let boldFont:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 17)!
let thirdFont:UIFont = UIFont(name: "HelveticaNeue-ThinItalic", size: 17)!

//Making dictionaries of fonts that will be passed as an attribute        

let firstDict:NSDictionary = NSDictionary(object: firstfont, forKey:  
NSFontAttributeName)
let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey: 
NSFontAttributeName)
let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey: 
NSFontAttributeName)

let firstText = "My name is "
let attributedString = NSMutableAttributedString(string: firstText, 
attributes: firstDict as? [String : AnyObject])

let boldText  = "Rajan"
let boldString = NSMutableAttributedString(string:boldText, 
attributes:boldDict as? [String : AnyObject])

let finalText = " iOS"
let finalAttributedString =  NSMutableAttributedString(string: 
finalText, attributes: thirdDict as? [String : AnyObject])

attributedString.appendAttributedString(boldString)
attributedString.appendAttributedString(finalAttributedString)
myLabel.attributedText = attributedString


Swift 3.0 편집

let firstfont:UIFont = UIFont(name: "Helvetica Neue", size: 17)!
let boldFont:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 17)!
let thirdFont:UIFont = UIFont(name: "HelveticaNeue-ThinItalic", size: 17)!

//Making dictionaries of fonts that will be passed as an attribute

let firstDict:NSDictionary = NSDictionary(object: firstfont, forKey:
        NSFontAttributeName as NSCopying)
let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey:
        NSFontAttributeName as NSCopying)
let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey:
        NSFontAttributeName as NSCopying)

let firstText = "My name is "
let attributedString = NSMutableAttributedString(string: firstText,
                                                     attributes: firstDict as? [String : AnyObject])

let boldText  = "Rajan"
let boldString = NSMutableAttributedString(string:boldText,
                                               attributes:boldDict as? [String : AnyObject])

let finalText = " iOS"
let finalAttributedString =  NSMutableAttributedString(string:
        finalText, attributes: thirdDict as? [String : AnyObject])

attributedString.append(boldString)
attributedString.append(finalAttributedString)
myLabel.attributedText = attributedString


Swift 4.0 편집

let firstfont:UIFont = UIFont(name: "Helvetica Neue", size: 17)!
let boldFont:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 17)!
let thirdFont:UIFont = UIFont(name: "HelveticaNeue-ThinItalic", size: 17)!

//Making dictionaries of fonts that will be passed as an attribute

let firstDict:NSDictionary = NSDictionary(object: firstfont, forKey:
    NSAttributedString.Key.font as NSCopying)
let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey:
    NSAttributedString.Key.font as NSCopying)
let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey:
    NSAttributedString.Key.font as NSCopying)

let firstText = "My name is "
let attributedString = NSMutableAttributedString(string: firstText,
                                                         attributes: firstDict as? [NSAttributedString.Key : Any])

let boldText  = "Rajan"
let boldString = NSMutableAttributedString(string:boldText,
                                                   attributes:boldDict as? [NSAttributedString.Key : Any])

let finalText = " iOS"
let finalAttributedString =  NSMutableAttributedString(string:
    finalText, attributes: thirdDict as? [NSAttributedString.Key : Any])

attributedString.append(boldString)
attributedString.append(finalAttributedString)
myLabel.attributedText = attributedString

이것은 다음과 같이 보일 것입니다

여기에 이미지 설명 입력


@Jason이 contentMode (텍스트 정렬) 지원을 추가하여 제안한 MultipartLabel을 업데이트했습니다.

MultipartLabel.h

#import <Foundation/Foundation.h>

@interface MultipartLabel : UIView {
}

@property (nonatomic,retain) UIView *containerView;
@property (nonatomic,retain) NSMutableArray *labels;
@property (nonatomic) UIViewContentMode contentMode;

- (void)updateNumberOfLabels:(int)numLabels;
- (void)setText:(NSString *)text forLabel:(int)labelNum;
- (void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum;
- (void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum;
- (void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum;

@end

MultipartLabel.m

//  MultipartLabel.m
//  MultipartLabel
//
//  Created by Jason Miller on 10/7/09.
//  Updated by Laurynas Butkus, 2011
//  Copyright 2009 Jason Miller. All rights reserved.
//

#import "MultipartLabel.h"

@interface MultipartLabel (Private)
- (void)updateLayout;
@end

@implementation MultipartLabel

@synthesize containerView;
@synthesize labels;
@synthesize contentMode;

-(void)updateNumberOfLabels:(int)numLabels
{
    [containerView removeFromSuperview];
    self.containerView = nil;

    self.containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)] autorelease];
    [self addSubview:self.containerView];
    self.labels = [NSMutableArray array];

    while (numLabels-- > 0) {
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.backgroundColor = self.backgroundColor;
        [self.containerView addSubview:label];
        [self.labels addObject:label];
        [label release];
    }

    [self updateLayout];
}

-(void)setText:(NSString *)text forLabel:(int)labelNum
{
    if( [self.labels count] > labelNum && labelNum >= 0 )
    {
        UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
        thisLabel.text = text;
    }

    [self updateLayout];
}

-(void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum
{
    if( [self.labels count] > labelNum && labelNum >= 0 )
    {
        UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
        thisLabel.text = text;
        thisLabel.font = font;
    }

    [self updateLayout];
}

-(void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum
{
    if( [self.labels count] > labelNum && labelNum >= 0 )
    {
        UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
        thisLabel.text = text;
        thisLabel.textColor = color;
    }

    [self updateLayout];
}

- (void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum
{
    if( [self.labels count] > labelNum && labelNum >= 0 )
    {
        UILabel * thisLabel = [self.labels objectAtIndex:labelNum];
        thisLabel.text = text;
        thisLabel.font = font;
        thisLabel.textColor = color;
    }

    [self updateLayout];
}

- (void)updateLayout {

    int thisX;
    int thisY;
    int totalWidth = 0;
    int offsetX = 0;

    int sizes[[self.labels count]][2];
    int i = 0;

    for (UILabel * thisLabel in self.labels) {
        CGSize size = [thisLabel.text sizeWithFont:thisLabel.font constrainedToSize:CGSizeMake(9999, 9999) 
                                     lineBreakMode:thisLabel.lineBreakMode];

        sizes[i][0] = size.width;
        sizes[i][1] = size.height;
        totalWidth+= size.width;

        i++;
    }

    i = 0;

    for (UILabel * thisLabel in self.labels) {
        // X
        switch (self.contentMode) {
            case UIViewContentModeRight:
            case UIViewContentModeBottomRight:
            case UIViewContentModeTopRight:
                thisX = self.frame.size.width - totalWidth + offsetX;
                break;

            case UIViewContentModeCenter:
                thisX = (self.frame.size.width - totalWidth) / 2 + offsetX;
                break;

            default:
                thisX = offsetX;
                break;
        }

        // Y
        switch (self.contentMode) {
            case UIViewContentModeBottom:
            case UIViewContentModeBottomLeft:
            case UIViewContentModeBottomRight:
                thisY = self.frame.size.height - sizes[i][1];
                break;

            case UIViewContentModeCenter:
                thisY = (self.frame.size.height - sizes[i][1]) / 2;
                break;

            default:
                thisY = 0;
                break;
        }

        thisLabel.frame = CGRectMake( thisX, thisY, sizes[i][0], sizes[i][1] );

        offsetX += sizes[i][0];

        i++;
    }
}

- (void)dealloc {
    [labels release];
    labels = nil;

    [containerView release];
    containerView = nil;

    [super dealloc];
}

@end

Use CoreText API it will be much faster.

Here are few examples

Basically the things you will have to do are: 1: Create UIView subclass 2: In the drawRect: method add the text drawing logic.

The text drawing logic: - You will need to know the range of the "name" so if Tom: Some message. is your string you will have to apply different font for range (0, 3).

You can customize everything with CoreText :)


Hi OHAttributelabel is good way for this.You can refer sample code with below link https://github.com/AliSoftware/OHAttributedLabel Import OHAttribute framwork from it and you can set your label as below

 OHAttributedLabel *lblText;
 lblText = [[OHAttributedLabel alloc] initWithFrame:CGRectMake(10,10,100,19)];
 lblText.backgroundColor = [UIColor clearColor];
    lblText.textAlignment = UITextAlignmentCenter;
    lblText.font = [UIFont fontWithName:@"BoschSans-Regular" size:10];
    NSString *strText=@"Tom: Some message.";
    NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString: strText];
    NSRange rangeOfSubstring = [strVersion rangeOfString:@“Tom:];
    if (rangeOfSubstring.location != NSNotFound) {
        [attrStr setFontName:@"BoschSans-BOLD" size:10.0 range:rangeOfSubstring];
    }
    else {
    }

    lblText.attributedText = attrStr;
    [self.View addSubview: lblText];

One option would be to use a UIWebView instead of UILabel.

예 : http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview


자신 만의 HTML 코드를 만드는 것은 아주 쉽습니다 =>

UIWebView *titleAd = [UIWebView alloc] init...;

NSString *cssString = [NSString stringWithFormat:@".title {font-family: HelveticaNeue; text-decoration: bold; font-size: %fpt; color: #4083a9;} .author {font-family: HelveticaNeue; text-decoration: bold; font-size: %fpt; color: #3e4545;}",__FONTSIZE_29__, __FONTSIZE_21__];

NSString *htmlString = [NSString stringWithFormat:@"<html> <head>     <style type=\"text/css\"> %@ </style> </head> <body>     <p>     <span class=\"title\"> %@ </span>     <span class=\"author\"> proposé par %@ </span>     </p> </body> </html>", cssString, [table title], [table nameOwner]];  

[titleAd loadHTMLString:htmlString baseURL:nil]; 

참고 URL : https://stackoverflow.com/questions/1417346/iphone-uilabel-tained-text-with-multiple-fonts-at-the-same-time

반응형