- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
如何在 uiLabel 中同时包含粗体和非粗体文本?
我宁愿不使用 UIWebView。我也读过这可能使用 NSAttributedString 但我不知道如何使用它。有什么想法吗?
Apple 在他们的几个应用中实现了这一点;示例截图:
谢谢!- 多姆
最佳答案
在 Swift 中,我们不必处理 iOS5 旧的东西,除了语法更短,所以一切都变得非常简单:
swift 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
}
Swift 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.strings 可用)
iOS6 UILabel
, UIButton
, UITextView
, UITextField
支持属性字符串,这意味着我们不需要创建 CATextLayer
s 作为属性字符串的接收者。此外,为了制作属性字符串,我们不再需要使用 CoreText 了 :) 我们在 obj-c Foundation.framework 中有新类,例如 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];
}
有几篇很好的介绍性博客文章 here invasivecode 的人用更多示例解释了 NSAttributedString
的用法,请查找 "iOS 6 的 NSAttributedString 简介" 和 "Attributed使用 Interface Builder 的 iOS 字符串" :)
PS:上面的代码应该可以工作,但它是大脑编译的。我希望这就足够了:)
使用 CATextLayer使用 NSAttributedString !比 2 个 UILabel 更轻更简单。 (iOS 3.2 及以上)
示例。
别忘了添加 QuartzCore 框架(CALayers 需要)和 CoreText(属性字符串需要)。
#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
下面的示例将向导航 Controller 的工具栏添加一个子层。 à la Mail.app 在 iPhone 中。 :)
- (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 attributes string keys .
关于ios - 单个 UILabel 中的粗体和非粗体文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3586871/
我有一个 UILabel,其不透明度已通过使用 [UIColor clearColor] 更改为空白我现在想将标签内文本的不透明度更改为尽可能完整的级别。我该怎么做? 最佳答案 使用以下代码更改UIL
我在同一个站点中阅读了如何插入和 UILabel(子类 UILabel 并覆盖所需的方法)。在将它添加到我的应用程序之前,我决定在一个独立的测试应用程序中对其进行测试。代码如下所示。 这是 MyUIL
NSString *longStr = @"AAAAAAAAAA\nBBBBB\nCCCCCCCCCCCCCCCCCC"; 如何使用 UILabel 截断某些标签宽度: AAA... BBB...
我想在 UILabel.text 上有一个纹理。 这样做我对 UILabel 进行了子类化。使用 -drawTextInRect 方法,我尝试仅获取用于使用 CGImageMaskCreate 函数创
我正在尝试使用 iOS 6.0 中新的自动布局 api 构建动态布局。我尝试构建的布局有 2 个按钮,它们之间有一个标签,如下图所示: 我想要的是以灰色显示的容器 View 根据标签中的文本量增加或减
我不知道这是否是我做错了什么,但每次 iOS 6 到 7、7 到 8 以及从 8 到 9 的重大更新时,一些 UILabel 似乎不够大,我看到“...”因为标签被截断了。我现在必须通过应用程序并重置
我偶然发现了一个我不确定如何解决的问题。 正如您在此处看到的名称应该所在的标签(我从用户输入中获取名称,这意味着它是动态的)。如果写得太长,它只会覆盖其他标签。 此外,在 Storyboard中,UI
我是初学者,所以对于任何似乎被忽视或简单的事情,我深表歉意。 基本上,我想要做的是让屏幕上的日期选择器更新 UILabel,然后获取更新 UILabel 的结果并将其推回到前一个屏幕上的另一个 UIL
我有一个 UILabel 的 NSMutableArray。我需要能够在用户触摸时选择此 NSMutableArray 中的特定 UILabel,并将此触摸 UILabel 的中心移动到用户将手指拖动
我知道对于类的元素 UIButton和 UIBarButtonItem他们自动假设window.tintColor作为主要颜色,如果我在应用程序中随时为窗口设置新的 tintColor,则会立即更改。
我是开发者世界的新人,自 2 月份以来一直断断续续地使用 swift 和 Xcode。我希望有人能帮助我。我正在尝试制作一个简单的小费计算器,但似乎无法将两个 uilabels 放在一起。这就是我到目
我有一个单元格原型(prototype),我正在尝试向其添加两个标签。我有两个紧挨着的标签,但标签的大小是动态的,所以我希望第二个标签能够根据第一个标签的大小移动。 基本上,我希望两个标签之间有一个固
这个问题看起来很平常..但是我昨天遇到了问题,我在 xib 中添加了一个标签并为其创建了导出,我想要在该标签内有多行,按钮,所以我决定添加新的子里面有标签... UILabel *label; lab
我正在尝试实现一个可以更改 uilabel 字体大小的功能,我可以缩放 uilabel 大小(即 uilabel.size),然后自动更改 uilabel 的字体大小,示例应用程序是 InstaTex
如果我设置bottomLabel.text = Chinese character,当我运行它时我看不到aboveLabel,如果我调试 View 层次我可以看到它。so有什么问题吗? UIL
我不太确定标题是否符合我的要求,但我有一个带有一堆句子的 label,我想将它们中的每一个分开到不同的 UILabel 这是我的代码 var s: [String] = [] for (i
当我更改 UILabel 的文本属性时,它只会在应用程序中部分更新。 我试过将它放在 viewDidLoad 函数和单独的专用函数中,但无济于事。如果我在更新后将 Label.text 打印到控制台,
我正在尝试使用自动布局对齐两个 UILabel,其中第一个标签没有设置宽度但使用固有内容大小,第二个应该与第一个宽度相同,将文本换行。 理想情况下,第二个标签应将数字行设置为 0 以使用动态类型,但我
我有几个标签,它们永远不应该相互接触。见下图(忽略黄色字母): 一共是4个标签,2个选手名字,2个分数。球员的名字将取代原来的球员标签文本。所以“玩家 1:”可以是任意宽度的任意文本。标签在 View
我正在开发一个应用程序,我需要能够点击并拖动 UILabels。第二个挑战是我需要屏幕上的其他 UILabel 相互移开(切勿重叠)。因此,当我拖动一个标签并遇到另一个标签时,它会将第二个标签撞开。也
我是一名优秀的程序员,十分优秀!