굵은 글씨와 굵은 글씨가 아닌 텍스트를 단일 UILabel로 표시합니까?
uiLabel에 굵은 글씨 텍스트와 굵은 글씨 텍스트를 모두 포함하려면 어떻게 해야 합니까?
UI WebView를 사용하지 않는 것이 좋습니다.또한 NSAttributedString을 사용할 수 있다고 읽었지만 사용 방법은 모르겠습니다.생각나는 거 없어요?
은 여러 앱에서 이를 달성합니다. 예: 스크린샷: Apple입니다. 네, 그렇습니다.
고마워요! - 돔!
갱신하다
Swift에서는 구문이 더 짧을 뿐 아니라 iOS5의 오래된 내용을 다룰 필요가 없습니다. 따라서 모든 것이 매우 단순해집니다.
스위프트 5입니다
func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
let fontSize = UIFont.systemFontSize
let attrs = [
NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
NSAttributedString.Key.foregroundColor: UIColor.black
]
let nonBoldAttribute = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
]
let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
if let range = nonBoldRange {
attrStr.setAttributes(nonBoldAttribute, range: range)
}
return attrStr
}
스위프트 3입니다
func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
let fontSize = UIFont.systemFontSize
let attrs = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
NSForegroundColorAttributeName: UIColor.black
]
let nonBoldAttribute = [
NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
]
let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
if let range = nonBoldRange {
attrStr.setAttributes(nonBoldAttribute, range: range)
}
return attrStr
}
용도는 다음과 같습니다.
let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)
let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()
보너스: 국제화입니다.
몇몇 사람들은 국제화에 대해 언급했습니다.저는 개인적으로 이 질문의 범위를 벗어난다고 생각하지만, 교육 목적으로는 이렇게 하겠습니다.
// Date we want to show
let date = Date()
// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
formatter.string(from: date))
// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))
// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
nil :
NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))
// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
nonBoldRange: nonBoldNSRange)
결과(영어 및 일본어 Localizable.string을 사용할 수 있다고 가정합니다.)
iOS6 이상에 대한 이전 답변(Objective-C는 여전히 작동합니다):
iOS6 iOS6에서는 다음과 같습니다.UILabel, , 입니다.UIButton, , 입니다.UITextView, , 입니다.UITextField, support attribute string은 우리가 만들지 않아도 된다는 의미입니다 , 즉, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, 를, ,, which, which, ,, ,.CATextLayer스스럼없이요., 더 이상 CoreText를 사용하지 않아도 속성 문자열을 만들기 위해 :) obj-c Foundation.framework에는 obj-c Foundation과 같은 새로운 클래스가 있습니다.NSParagraphStyle네! 네! 네! 네! 네!
다음 문자열이 있습니다.
NSString *text = @"Updated: 2012/10/14 21:59"
다음 속성 문자열만 생성하면 됩니다.
if ([_label respondsToSelector:@selector(setAttributedText:)])
{
// iOS6 and above : Use NSAttributedStrings
// Create the attributes
const CGFloat fontSize = 13;
NSDictionary *attrs = @{
NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
NSForegroundColorAttributeName:[UIColor whiteColor]
};
NSDictionary *subAttrs = @{
NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
};
// Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
// This example is about attributed strings in one label
// not about internationalisation, so we keep it simple :)
// For internationalisation example see above code in swift
const NSRange range = NSMakeRange(8,12);
// Create the attributed string (text + attributes)
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attrs];
[attributedText setAttributes:subAttrs range:range];
// Set it in our UILabel and we are done!
[_label setAttributedText:attributedText];
} else {
// iOS5 and below
// Here we have some options too. The first one is to do something
// less fancy and show it just as plain text without attributes.
// The second is to use CoreText and get similar results with a bit
// more of code. Interested people please look down the old answer.
// Now I am just being lazy so :p
[_label setText:text];
}
여기 침습 코드의 남성들이 쓴 좋은 소개 블로그 게시물 몇 개가 있습니다. 더 많은 예시로 설명됩니다.NSAttributedString, "NSAttributedString for iOS 6 소개" 및 "Interface Builder를 사용한 iOS의 속성 문자열"을 찾습니다.
PS: 코드 위에서는 작동해야 하지만 두뇌 컴파일 되어 있습니다.충분했으면 좋겠네요:)
iOS5 이하에 대한 오래된 답변입니다.
NSAttributedString!이 2개의 UILabel보다 훨씬 가볍고 간단한 CATextLayer를 사용합니다(iOS 3.2 이상).
예.
QuartzCore 프레임워크(CALayer에 필요)와 CoreText(속성 문자열에 필요)를 추가하는 것을 잊지 마십시오.
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
아래 예에서는 탐색 컨트롤러의 도구 모음에 하위 계층을 추가합니다.iPhone에서 Mail.app을 참조하십시오.:)
- (void)setRefreshDate:(NSDate *)aDate
{
[aDate retain];
[refreshDate release];
refreshDate = aDate;
if (refreshDate) {
/* Create the text for the text layer*/
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy hh:mm"];
NSString *dateString = [df stringFromDate:refreshDate];
NSString *prefix = NSLocalizedString(@"Updated", nil);
NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString];
[df release];
/* Create the text layer on demand */
if (!_textLayer) {
_textLayer = [[CATextLayer alloc] init];
//_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
_textLayer.backgroundColor = [UIColor clearColor].CGColor;
_textLayer.wrapped = NO;
CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
_textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
_textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
_textLayer.alignmentMode = kCAAlignmentCenter;
[layer addSublayer:_textLayer];
}
/* Create the attributes (for the attributed string) */
CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
UIFont *font = [UIFont systemFontOfSize:13];
CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
CGColorRef cgColor = [UIColor whiteColor].CGColor;
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
(id)ctBoldFont, (id)kCTFontAttributeName,
cgColor, (id)kCTForegroundColorAttributeName, nil];
CFRelease(ctBoldFont);
NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil];
CFRelease(ctFont);
/* Create the attributed string (text + attributes) */
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
[attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ "
/* Set the attributes string in the text layer :) */
_textLayer.string = attrStr;
[attrStr release];
_textLayer.opacity = 1.0;
} else {
_textLayer.opacity = 0.0;
_textLayer.string = nil;
}
}
이 예에서는 두 가지 글꼴 유형(굵은 글꼴과 일반 글꼴)만 사용하지만 글꼴 크기, 색상, 기울임꼴, 밑줄 등을 사용할 수도 있습니다.NSAttributedString / NSMutableAttributedString 및 CoreText 특성 문자열 키를 살펴보십시오.
UILabel에서 범주를 사용해 보십시오.
사용 방법은 다음과 같습니다.
myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
그리고 여기 범주가 있습니다.
UILabel+Boldify.h를 클릭합니다.
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
UILabel+Boldify.m을 클릭합니다.
- (void) boldRange: (NSRange) range {
if (![self respondsToSelector:@selector(setAttributedText:)]) {
return;
}
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
self.attributedText = attributedText;
}
- (void) boldSubstring: (NSString*) substring {
NSRange range = [self.text rangeOfString:substring];
[self boldRange:range];
}
이 기능은 iOS 6 이상에서만 작동합니다.iOS 5 이전 버전에서는 무시됩니다.
이는 Interface Builder에서 쉽게 수행할 수 있습니다.
1) 특성 검사기에서 UILabel Attributed로 만듭니다.

2) 굵은 글씨로 표현하고 싶은 구절을 선택합니다.

3) 글꼴 선택기에서 글꼴(또는 같은 글꼴의 굵은 글꼴)을 변경합니다.

그게 다예요!
bbrame의 카테고리에 따른 bbrame은 bbrame입니다.비슷하게 동작하지만, 같은 글씨로 굵은 글씨로 표현할 수 있습니다.UILabel여러 번 반복하여 누적 결과를 얻을 수 있습니다.
UILabel+Boldify.h를 클릭합니다.
@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end
UILabel+Boldify.m을 클릭합니다.
@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
if (![self respondsToSelector:@selector(setAttributedText:)]) {
return;
}
NSMutableAttributedString *attributedText;
if (!self.attributedText) {
attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
} else {
attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
}
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
self.attributedText = attributedText;
}
- (void)boldSubstring:(NSString*)substring {
NSRange range = [self.text rangeOfString:substring];
[self boldRange:range];
}
@end
이 수정을 통해 다음과 같이 여러 번 사용할 수 있습니다.
myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
는 "업데이트됨: 2012/10/14 21:59 PM"으로 표시됩니다.
제게는 효과가 있었어요
CGFloat boldTextFontSize = 17.0f;
myLabel.text = [NSString stringWithFormat:@"%@ 2012/10/14 %@",@"Updated:",@"21:59 PM"];
NSRange range1 = [myLabel.text rangeOfString:@"Updated:"];
NSRange range2 = [myLabel.text rangeOfString:@"21:59 PM"];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:myLabel.text];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
range:range2];
myLabel.attributedText = attributedText;
Swift 버전의 경우:여기를 참조하십시오.
스위프트의 확장자에 대한 크레이지 요거트의 답변을 채택했습니다.
extension UILabel {
func boldRange(_ range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
func boldSubstring(_ substr: String) {
if let text = self.attributedText {
var range = text.string.range(of: substr)
let attr = NSMutableAttributedString(attributedString: text)
while range != nil {
let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
var nsRange = NSMakeRange(start, length)
let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
break
}
range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
}
if let r = range {
boldRange(r)
}
}
}
}
Range와 NSRange 간의 변환이 좋지 않을 수 있지만, 더 나은 것을 찾지 못했습니다.
TTTttributedLabel을 확인하십시오.NSAttributedString을 해당 레이블의 텍스트로 설정하여 단일 레이블에서 글꼴과 색상을 혼합할 수 있는 UILabel의 드롭다운 대체 기능입니다.
이 경우엔 시도해 보세요
UILabel *displayLabel = [[UILabel alloc] initWithFrame:/*label frame*/];
displayLabel.font = [UIFont boldSystemFontOfSize:/*bold font size*/];
NSMutableAttributedString *notifyingStr = [[NSMutableAttributedString alloc] initWithString:@"Updated: 2012/10/14 21:59 PM"];
[notifyingStr beginEditing];
[notifyingStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:/*normal font size*/]
range:NSMakeRange(8,10)/*range of normal string, e.g. 2012/10/14*/];
[notifyingStr endEditing];
displayLabel.attributedText = notifyingStr; // or [displayLabel setAttributedText: notifyingStr];
UILabel에서 텍스트와 밑줄을 굵게 표시합니다.코드에 다음 줄을 추가하세요.
NSRange range1 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_terms", @"")];
NSRange range2 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_policy", @"")];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:lblTermsAndCondition.text];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
range:range2];
[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:range1];
[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
range:range2];
lblTermsAndCondition.attributedText = attributedText;
NSString *needToChangeStr=@"BOOK";
NSString *display_string=[NSString stringWithFormat:@"This is %@",book];
NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:display_string];
int begin=[display_string length]-[needToChangeStr length];
int end=[needToChangeStr length];
[attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30] range:NSMakeRange(begin, end)];
Swift 4: 입니다.
// attribute with color red and Bold
var attrs1 = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red]
// attribute with color black and Non Bold
var attrs2 = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 20), NSAttributedStringKey.foregroundColor: UIColor.black]
var color1 = NSAttributedString(string: "RED", attributes: attrs1)
var color2 = NSAttributedString(string: " BLACK", attributes: attrs2)
var string = NSMutableAttributedString()
string.append(color1)
string.append(color2)
// print the text with **RED** BLACK
print("Final String : \(string)")
처리할 문자열을 입력으로 제공하고 굵은 글씨/색상의 단어를 입력으로 입력합니다.
func attributedString(parentString:String, arrayOfStringToProcess:[String], color:UIColor) -> NSAttributedString
{
let parentAttributedString = NSMutableAttributedString(string:parentString, attributes:nil)
let parentStringWords = parentAttributedString.string.components(separatedBy: " ")
if parentStringWords.count != 0
{
let wordSearchArray = arrayOfStringToProcess.filter { inputArrayIndex in
parentStringWords.contains(where: { $0 == inputArrayIndex }
)}
for eachWord in wordSearchArray
{
parentString.enumerateSubstrings(in: parentString.startIndex..<parentString.endIndex, options: .byWords)
{
(substring, substringRange, _, _) in
if substring == eachWord
{
parentAttributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 15), range: NSRange(substringRange, in: parentString))
parentAttributedString.addAttribute(.foregroundColor, value: color, range: NSRange(substringRange, in: parentString))
}
}
}
}
return parentAttributedString
}
Swift에서 방금 프로젝트에 구현한 다음 코드를 사용하여 NSRange를 수행할 필요가 없습니다.
//Code sets label (yourLabel)'s text to "Tap and hold(BOLD) button to start recording."
let boldAttribute = [
//You can add as many attributes as you want here.
NSFontAttributeName: UIFont(name: "HelveticaNeue-Bold", size: 18.0)!
]
let regularAttribute = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 18.0)!]
let beginningAttributedString = NSAttributedString(string: "Tap and ", attributes: regularAttribute )
let boldAttributedString = NSAttributedString(string: "hold ", attributes: boldAttribute)
let endAttributedString = NSAttributedString(string: "button to start recording.", attributes: regularAttribute )
let fullString = NSMutableAttributedString()
fullString.appendAttributedString(beginningAttributedString)
fullString.appendAttributedString(boldAttributedString)
fullString.appendAttributedString(endAttributedString)
yourLabel.attributedText = fullString
속성 문자열을 보다 쉽게 사용하려면 코드를 생성하는 속성 문자열 생성기를 사용해 보십시오.https://itunes.apple.com/us/app/attributed-string-creator/id730928349
AttributeString에는 문자열을 마크다운하는 생성자가 있습니다. 이렇게 하면 속성 문자열에 다른 속성이 없을 수 있으므로 xib를 사용하는 경우 굵은 글씨 없이 텍스트를 원하는 다른 모든 속성으로 설정할 수 있습니다.그런 다음 코드 내에서 마크 다운 문자열의 속성 범위를 열거하고 xib 파일에서 얻은 속성 문자열에 적용한 다음 특정 필드의 속성 attributeString에 다시 적용합니다.
언급URL : https://stackoverflow.com/questions/3586871/bold-non-bold-text-in-a-single-uilabel 입니다.
'programing' 카테고리의 다른 글
| SQL Server Management Studio에서 "실제" CSV 형식으로 내보내기 출력을 얻는 방법은 무엇입니까? (0) | 2023.04.25 |
|---|---|
| C# 작업 스케줄링 라이브러리를 권장합니다. (0) | 2023.04.25 |
| Eclipse: 파일 이름을 빠르게 검색합니다. (0) | 2023.04.25 |
| 도메인이 여러 개인 Access-Control-allow-origin입니다. (0) | 2023.04.25 |
| 배치를 사용하여 xlsx 파일을 csv로 변환합니다. (0) | 2023.04.25 |

