Development Tip

NSString의 일부를 굵게 표시하는 방법은 무엇입니까?

yourdevel 2020. 10. 25. 13:11
반응형

NSString의 일부를 굵게 표시하는 방법은 무엇입니까?


문자열의 일부만 굵게 표시 할 수있는 방법이 있습니까? 예를 들면 :

대략적인 거리 : 120m 거리

감사!


당신이 할 있는 것은 NSAttributedString.

NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName 
                   value:boldFontName
                   range:boldedRange];

[attrString endEditing];
//draw attrString here...

핵심 텍스트로 개체 를 그리는 방법 에 대한 이 편리한 멋진 가이드살펴보세요 NSAttributedString.


Jacob이 언급했듯이 아마도 NSAttributedString또는 NSMutableAttributedString. 다음은이를 수행하는 방법의 한 예입니다.

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Approximate Distance: 120m away"];
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22

[string beginEditing];

[string addAttribute:NSFontAttributeName
           value:[NSFont fontWithName:@"Helvetica-Bold" size:12.0]
           range:selectedRange];

[string endEditing];

글꼴에 신경 쓰지 않으려면 (모든 글꼴 변형에 "굵게"가 포함되어 있지는 않으므로) 여기에 다른 방법이 있습니다. 현재 OS X에서만 사용할 수 있습니다.

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"];
[attrString beginEditing];
[attrString applyFontTraits:NSBoldFontMask
                      range:NSMakeRange(22, 4)];
[attrString endEditing];

위의 코드는이 attributeString으로 UILabel을 만들 때 충돌을 일으켰습니다.

이 코드를 사용했고 작동했습니다.

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSRange boldedRange = NSMakeRange(0, 1);
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:@"Lato-Bold" size:12];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];

빠른

또한 동적으로 강조하려는 문자열의 범위를 가져옵니다.

let nameString = "Magoo"
let string = "Hello my name is \(nameString)"

let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]

let attributedString = NSMutableAttributedString(string: string, attributes: attributes)

let nsString = NSString(string: string)
let range = nsString.rangeOfString(nameString)

if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }

someLabel.attributedText = attributedString

글꼴을 하드 코딩하지 않고 문자열을 굵게 표시하려면 StrokeWidth 속성을 음수 값과 함께 사용할 수 있습니다.

let s = NSMutableAttributedString(string: "Approximate Distance: 120m away")
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26))

An NSString은 데이터 컨테이너 일뿐입니다. 프레젠테이션 문제에 대한 세부 정보는 포함되어 있지 않습니다.

아마도 당신이 원하는 UILabel것은 문자열을 표시하는 데 사용되는 의 굵은 부분 인 것 같습니다 . 나는 당신이 할 수 있다고 생각하지 않습니다. 그러나 항상 UI를 "대략적인 거리 :"에 대한 레이블, " 120m "에 대한 레이블 및 "멀리에 대한" 레이블의 세 개로 나눌 수 있습니다. 그것들을 서로 일렬로 배치하면 원하는 효과를 얻을 수 있습니다.

Another option might be to use a UIWebView and a little bit of markup to display your string with embedded formatting information, as discussed here:

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


In Xamarin ios you can bold part of a NSString this way:

public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange)
    {
        var firstAttributes = new UIStringAttributes {
            Font = UIFont.BoldSystemFontOfSize(fontSize)
        };

        NSMutableAttributedString boldString = new NSMutableAttributedString (str);
        boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange));
        return boldString;
    }    

and call this method:

myLabel = new UILabel (); 
...
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);    

I coupled @Jacob Relkin and @Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:

UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = @"Approximate Distance: 120m away";
NSRange boldedRange = NSMakeRange(22, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName 
                   value:boldFont
                   range:boldedRange];

[attrString endEditing];

I took a look at the official documentation: 1 and 2.


If you don't want to hardcode the font or/and the size try this code for bolding full strings:

NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:mainString];
[myString beginEditing];
[myString addAttribute:NSStrokeWidthAttributeName
                         value:[[NSNumber alloc] initWithInt: -3.f]
                         range:NSMakeRange(0, [mainString length])];
[myString endEditing];

참고URL : https://stackoverflow.com/questions/6013705/any-way-to-bold-part-of-a-nsstring

반응형