iOS 부 텍스트 사용 방법 예시 상세 설명

머리말
항상 한 단락 의 문자 가 서로 다른 색상 과 글꼴 을 표시 하거나,몇 개의 문자 에 삭제 선 이나 밑줄 을 그 어야 하 는 수요 가 있 습 니 다.
부 텍스트 NSMuttableAttstring(속성 이 있 는 문자열)을 사용 하면 위의 일부 수 요 를 간편 하 게 실현 할 수 있 습 니 다.
최근 에 하나의 기능 을 실현 하고 싶 습 니 다.그림 과 같 습 니 다.

매월 가격
처음 이 루어 졌 을 때 두 개의 레이 블 로 이 루어 질 것 을 생각 했 습 니 다.첫 번 째 디 스 플레이¥4000,하나의 글꼴,두 번 째 디 스 플레이/월,다른 글꼴 을 설정 하면 이 효 과 를 실현 할 수 있 습 니 다.하지만 마지막 으로 생각해 보 니 부 텍스트 를 사용 하 는 것 이 좋 습 니 다.참고 로 배 울 수 있 습 니 다.
오늘 우 리 는 먼저 이 간단 한 효 과 를 실현 한다.
먼저 레이 블 을 만 듭 니 다:

-(UILabel *)priceLabel{
 if (_priceLabel == nil) {
 _priceLabel = [[UILabel alloc]init];
 _priceLabel.font = kFONT(13);
 _priceLabel.textColor = kColorTheme;
 _priceLabel.textAlignment = NSTextAlignmentRight;
 }
 return _priceLabel;
}
스스로 개인 적 인 방법 을 만 들 고 문자열(예 를 들 어¥4000/월)을 들 여 와 서 변환 하고 부 텍스트 로 돌아 가 필요 한 Label 에 값 을 부여 합 니 다.

-(NSMutableAttributedString *)getPriceAttribute:(NSString *)string{
 
 NSMutableAttributedString *attribut = [[NSMutableAttributedString alloc]initWithString:string];
 //       ‘/'        ,       range
 NSRange range = [string rangeOfString:@"/"];
 NSRange pointRange = NSMakeRange(0, range.location);
 NSMutableDictionary *dic = [NSMutableDictionary dictionary];
 dic[NSFontAttributeName] = [UIFont systemFontOfSize:18];
 //  
 [attribut addAttributes:dic range:pointRange]; 
 return attribut;
}
먼저 부 텍스트 NSMutable AttributedString 대상 을 만 들 고 들 어 오 는 NSString 대상 을 NSMutable AttributedString 대상 으로 전환 합 니 다.
그리고 NSMutable AttributedString 을 설정 합 니 다.NSRange range = [string rangeOfString:@"/"];표지 의 위 치 를 가 져 온 다음 에'/'앞의 문 자 를 설정 합 니 다.
그리고 부 텍스트 로 돌아 가 값 을 부여 합 니 다.

 _priceLabel.attributedText = [self getPriceAttribute:@"¥4000/ "]; 
위 에는 간단 한 응용 일 뿐 이 고 자주 사용 되 는 부 텍스트 도 많다.예 를 들 어 문자 와 그림 의 혼합,문자 클릭 사건 등 이다.
우 리 는 차례대로 몇 가지 기능 을 실현 한다.
지정 한 위치 에 그림 추가

NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"         ,              "];
[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, 5)];
[attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0, 5)];
지정 한 위치 에 그림 추가

NSTextAttachment *attchImage = [[NSTextAttachment alloc] init];
//     
attchImage.image = [UIImage imageNamed:@"pic3"];
//       
attchImage.bounds = CGRectMake(0, -5, 20, 20);
NSAttributedString *stringImage = [NSAttributedString attributedStringWithAttachment:attchImage];
[attriStr insertAttributedString:stringImage atIndex:2];
마지막 까지 사진 추가

NSTextAttachment *attch = [[NSTextAttachment alloc] init];
//     
attch.image = [UIImage imageNamed:@"pic2"];
//       
attch.bounds = CGRectMake(0, -5, 20, 15);
//           
NSAttributedString *string = [NSAttributedString attributedStringWithAttachment:attch];
[attriStr appendAttributedString:string];
중간 위 치 를 빨간색 으로 설정 합 니 다.

[attriStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6, 4)];
[attriStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:30] range:NSMakeRange(6, 4)];
종합 표기 법

NSDictionary * attriBute = @{NSForegroundColorAttributeName:[UIColor yellowColor],NSFontAttributeName:[UIFont systemFontOfSize:25]};
[attriStr addAttributes:attriBute range:NSMakeRange(10, 4)];
self.attrobiuteLabel.attributedText = attriStr;
효과 그림:

마지막 으로 각 속성의 뜻 을 알 아 보 자.

// NSFontAttributeName          ,   :  :Helvetica(Neue)   :12
// NSForegroundColorAttributeNam        ,    UIColor  ,      
// NSBackgroundColorAttributeName              ,    UIColor  ,    nil,    
// NSLigatureAttributeName         ,   NSNumber   (  ),0         ,1            
// NSKernAttributeName          ,    NSNumber   (  ),      ,      
// NSStrikethroughStyleAttributeName      ,    NSNumber   (  )
// NSStrikethroughColorAttributeName        ,    UIColor   ,      
// NSUnderlineStyleAttributeName       ,    NSNumber   (  ),     NSUnderlineStyle   ,      
// NSUnderlineColorAttributeName         ,    UIColor   ,      
// NSStrokeWidthAttributeName         ,    NSNumber   (  ),      ,      
// NSStrokeColorAttributeName         ,      ,    UIColor   
// NSShadowAttributeName          ,    NSShadow   
// NSTextEffectAttributeName           ,    NSString   ,            :
// NSBaselineOffsetAttributeName         ,    NSNumber (float),    ,    
// NSObliquenessAttributeName          ,    NSNumber (float),    ,    
// NSExpansionAttributeName             ,    NSNumber (float),        ,        
// NSWritingDirectionAttributeName         ,              
// NSVerticalGlyphFormAttributeName         ,    NSNumber   (  ),0       ,1       
// NSLinkAttributeName          ,            URL  
// NSAttachmentAttributeName         ,   NSTextAttachment  ,         
// NSParagraphStyleAttributeName            ,    NSParagraphStyle   
격식&조판
위의 속성의 마지막 은 레이아웃 입 니 다.NSMutable ParagraphStyle 의 대상 으로 가 야 합 니 다.코드 를 직접 올 려 주세요.

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.alignment = aligent;
paragraphStyle.lineSpacing = lineSpace; //      
paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;//    
NSRange range = NSMakeRange(0, [string length]);
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
NSMutable ParagraphStyle 의 속성 을 다시 한 번 알 아 보 겠 습 니 다.

CGFloat lineSpacing;     //        
CGFloat paragraphSpacing;   //          
NSTextAlignment alignment;   // (     )      ( , , ,    ,  ) 
CGFloat firstLineHeadIndent;   //      
CGFloat headIndent;     //     (    ) 
CGFloat tailIndent;     //     
NSLineBreakMode lineBreakMode;  //         ……    
CGFloat minimumLineHeight;   //     
CGFloat maximumLineHeight;   //      
NSWritingDirection baseWritingDirection; //     
CGFloat lineHeightMultiple;   //       
CGFloat paragraphSpacingBefore;  //       
float hyphenationFactor;    //       iOS,         0 1 
이렇게 많은 형식 을 설정 하고 여러 가지 조판 을 진행 하 였 는데 어떻게 높이 를 계산 합 니까?

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(nullable NSStringDrawingContext *)context NS_AVAILABLE(10_11, 6_0);
애플 이 추천 하 는 계산 방법 입 니 다.줄 간격,들 여 쓰기 등 형식 설정 에 문제 가 있 을 수 있 습 니 다.attributes 가 들 어 오 는 사전 에는 우리 가 설정 한 글꼴 과 형식 이 포함 되 어 있 습 니 다.그 중에서 NSParagraphStyleAttributeName 은 단락 스타일 을 설정 하고 NSFontAttributeName 은 글꼴 을 설정 합 니 다.
총결산
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.

좋은 웹페이지 즐겨찾기