1

기본적으로 기본 글꼴이있는 NSAttributedString을 생성하려고하는데 이탤릭체와 다른 텍스트 색상이 있습니다. 지금까지는 충분히 쉽습니다.NSAttributedString with UIFontWeightTraits

이제 전체 문자열의 다른 하위 문자열을 으로 변경하고을 굵게 표시합니다. 기본적으로 다음과 같아야합니다.

존 스미스 on 25.08. 나는 내가 NSMutableAttributedStringaddAttributes(_:_:) 함수에 전달할 것을 사전이 잘못된 얻는 것 같은 8시

에 (그냥 다른 색.)

것 같습니다.

[UIFontDescriptorTraitsAttribute: 
    [UIFontWeightTrait: NSNumber(double: Double(UIFontWeightBold))] 

을하지만이 작동하지 않는 것 다음 documentation에서,이 사전은 다음과 같이해야한다고 이해했다. 결국 나는 문자열의 이탤릭체 버전입니다. 나는 분명히 뭔가 잘못되고있다. 어떤 생각?

업데이트 : 추가 간단한 예

// Preparation 
let rawString = "from John Smith on 25.08. at 8:00" 
let attributedString = NSMutableAttributedString(string: rawString) 
let nameRange = (rawString as NSString).rangeOfString("John Smith") 
let italicFont = UIFont.italicSystemFontOfSize(14) 

// Make entire string italic: works! 
attributedString.addAttributes([NSFontAttributeName : italicFont], range: NSMakeRange(0, 33)) 
// Make the name string additionally bold: doesn't work! 
attributedString.addAttributes([UIFontDescriptorTraitsAttribute: 
     [UIFontWeightTrait: NSNumber(double: Double(UIFontWeightBold))]], range: nameRange) 

// Show it on the label 
attributedStringLabel.attributedText = attributedString 

감사합니다!

+0

여러 속성 문자열을 가지고 보여 하나에 결합해야합니다. –

+0

위의 함수를 사용하여 사실을 추가 한 후에 추가 할 수 없다는 것을 의미합니까? – flohei

답변

1

UIFontDescriptorTraitsAttributeNSAttributedString에서 인정 키를 사전 속성되지 않으므로 당신이 UIFont를 재구성하고 NSFontAttributeName 키를 사용하는 데 필요한 특성을 획득하는 데.

//prepare the fonts. we derive the bold-italic font from the italic font 
    let italicFont = UIFont.italicSystemFontOfSize(14) 
    let italicDesc = italicFont.fontDescriptor() 
    let italicTraits = italicDesc.symbolicTraits.rawValue 
    let boldTrait = UIFontDescriptorSymbolicTraits.TraitBold.rawValue 
    let boldItalicTraits = UIFontDescriptorSymbolicTraits(rawValue:italicTraits | boldTrait) 
    let boldItalicDescriptor = italicDesc.fontDescriptorWithSymbolicTraits(boldItalicTraits) 
    let boldItalicFont = UIFont(descriptor: boldItalicDescriptor, size: 0.0) 

    //prepare the string 
    let rawString = "from John Smith on 25.08. at 8:00" 
    let attributedString = NSMutableAttributedString(string: rawString) 

    let fullRange = NSMakeRange(0, 33) 
    let nameRange = (rawString as NSString).rangeOfString("John Smith") 

    attributedString.addAttributes([NSFontAttributeName:italicFont], range: fullRange) 
    attributedString.addAttributes([NSFontAttributeName:boldItalicFont], range: nameRange) 

도 참조 : NSAttributedString: Setting FontAttributes doesn't change font

+0

신난다, 고마워. 이것이 제가 찾고 있던 것입니다. 전에 이런 접근법을 보았지만 어디서 어떻게 작동했는지 기억하지 못했습니다. 감사! – flohei