我已经看了大约10个关于SO的问题,而且我仍然很短.
我有一个多行UILabel(在Interface Builder中创建,numberOfLines设置为0),它通常像这样呈现:

我想强调"服务条款"和"隐私政策",所以我添加了以下代码:
NSString *text = self.agreement.text;
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:text];
NSRange privacyRange = [text rangeOfString:@"privacy policy" options:NSCaseInsensitiveSearch];
[aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:privacyRange];
NSRange tosRange = [text rangeOfString:@"terms of service" options:NSCaseInsensitiveSearch];
[aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:tosRange];
self.agreement.attributedText = aString;
Run Code Online (Sandbox Code Playgroud)
但结果如下:

我需要做什么才能显示这两行,并用适当的范围加下划线?
此外,我不想使用像OHAttributedLabel或TTTAttributedLabel这样的第三方库,因为这是我的应用中唯一需要为一段文字加下划线的地方.
我试过的
sizeToFit设置属性文本后调用numberOfLines和lineBreakMode代码Sascha让我上传了两个截图,背景颜色设置为清除之外的其他颜色.奇怪的是,一切都按预期显示!不知道该怎么做或这告诉我们什么.

objective-c nsattributedstring uilabel ios nsmutableattributedstring
我想在中显示带有<blockquote>标签的HTML文本UITextView.
HTML的例子:
<div>
<blockquote class="uncited">
<div>
<cite>Nick:</cite>
<blockquote class="uncited">
<div>
<cite>Tom:</cite>censored<br>
Hello
</div>
</blockquote>
<p>World</p>
</div>
</blockquote>
<p>Text</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我使用以下代码在单元格中显示HTML文本:
UITextView *textView = (UITextView*)[cell viewWithTag:100];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[thisComment.htmlText dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)
但UITextView它看起来像纯文本.我想得到它:样本
我该怎么做?我应该使用什么样的库?我想想HTML -> Markdown -> NSAttributedString -> TextView
想要更改html标签的对齐方式.什么都行不通.我没有在HTML中看到任何CSS.没有进一步的设置改变对齐方式.我还在UILabel上直接设置左对齐.我错过了什么?
代码是UILabel扩展名.
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
NSDictionary *attr = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding), NSParagraphStyleAttributeName: paragraphStyle};
NSError *error = nil;
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc]initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:attr documentAttributes:nil error:&error];
// also tried with this
[attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle
range:NSMakeRange(0, html.length)
];
self.attributedText = attributedText;
Run Code Online (Sandbox Code Playgroud)
编辑
好的,所以我创建了一个单独的项目,默认情况下,文本保持对齐.我必须找出为什么在上面的例子中文本显示合理.在任何情况下,主要问题仍然存在,我无法更改默认对齐方式.它在使用时初始化属性字符串时有效initWithString.但在这种情况下,HTML不起作用.当initWithData像上面的例子一样,html工作但对齐不起作用.
运行此代码段,您将看到.
UILabel *label = [[UILabel alloc] init];
label.frame = CGRectMake(50, 50, 300, 400);
label.backgroundColor = [UIColor yellowColor];
label.numberOfLines = 0;
label.textAlignment = NSTextAlignmentRight;
NSString …Run Code Online (Sandbox Code Playgroud) 更新1
我找到了解决办法:
// instead of
font = [font fontWithSize:pointSize];
// i can do this and get the correct font back
font = [UIFont fontWithName:font.fontName size:pointSize]
Run Code Online (Sandbox Code Playgroud)
我正在使用Nick Lockwood的HTMLLabel类将HTML转换为一个尊重HTML中样式的NSAttributedString.在大多数情况下,它很有效.
但是,我在我的应用程序中使用自定义字体,出于某种原因,我的字体总是以粗体显示.我没有使用系统字体的这个问题.我把它缩小到这个方法:
- (UIFont *)font
{
// ** Code Path 1 **
UIFont *font = _styles[HTMLFont];
if ([font isKindOfClass:[NSString class]])
{
font = [UIFont fontWithName:(NSString *)font size:17.0f];
}
NSInteger pointSize = [_styles[HTMLTextSize] floatValue] ?: font.pointSize;
if (self.bold) {
if (self.italic)
{
font = [font boldItalicFontOfSize:pointSize];
}
else
{
font = [font boldFontOfSize:pointSize]; …Run Code Online (Sandbox Code Playgroud) 我想更改单词中括号的基线偏移量,例如“[\xe6\x8e\xa8]blablabla”。
\n\nNSRange range = [text rangeOfString:@"[\xe6\x8e\xa8]"];\nif (range.location == 0) {\n [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(0, 1)];\n [text addAttribute:NSBaselineOffsetAttributeName value:@(0.5) range:NSMakeRange(range.length-1, 1)];\n}\nRun Code Online (Sandbox Code Playgroud)\n\n但标签的第二行消失并被截断。有人有主意吗?
\n let paragraph = NSMutableParagraphStyle()
paragraph.alignment = NSTextAlignment.right
paragraph.tailIndent = -3
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowColor = UIColor.gray
shadow.shadowOffset = CGSize(width: 2, height: -2)
let text = NSMutableAttributedString(string: "MY LABEL", attributes:
[NSShadowAttributeName : shadow,
NSStrokeColorAttributeName : UIColor.black,
NSStrokeWidthAttributeName : -3,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName : UIFont(name: "MyFont", size: 24) as Any,
NSParagraphStyleAttributeName : paragraph])
let node = SKLabelNode()
addChild(node)
node.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
它有效,但没有阴影。我可以使用相同的NSMutableAttributedString上著名的ASAttributedLabel和它的作品不错,有一个影子,但我想使用SKLabelNode,以实现更好的性能IOS11。ASAttributedLabel可能会滞后于动态场景:(
nsattributedstring nsmutableattributedstring sprite-kit sklabelnode swift
我有一个带有大文本的 uitextview,上面有一个搜索字段。搜索任何内容,我都希望 uitextview 滚动到该特定文本和突出显示。而且我需要确保 uitextview 以这样一种方式滚动,即搜索到的文本保留在第一行
我用一些属性的属性文本填充了文本视图。我尝试的是在目标文本之前获取文本,并尝试获取它的大小,添加我在开始时在 textview 文本上添加的确切属性。
使用该高度制作了一个 CGPoint 并设置了 uitextview 的 contentOffset。但是文本视图在目标文本附近没有滚动。也许我的方法是错误的,因为我在设置属性时没有 textview 的宽度
我的代码是:
func goToBla() {
if let string = ayatTextView.text {
if let range = string.range(of: tazweedAyahas[8].text) {
let firstPart = string[string.startIndex..<range.lowerBound]
print("before \(tazweedAyahas[5].text) : ")
print(firstPart)
if let otherStr = firstPart as? NSString {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let size = otherStr.size(withAttributes: [NSAttributedStringKey.paragraphStyle: paragraphStyle,
NSAttributedStringKey.font: UIFont(name: "me_quran", size: 30)
])
let point = CGPoint(x: 0, y: size.height)
ayatTextView.setContentOffset(point, animated: true) …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个自定义NSTextBlock,就像Apple在WWDC 18上(在23分钟内)所做的那样。
好的,所以当我用带有文本块的段落样式编辑和标记段落时,它的效果很好。
但是,当我剪切并粘贴它(或从磁盘归档/取消归档)时,它将丢失。编辑:它实际上将我的TweetTextBlock子类转换为NSTableViewTextBlock,这也说明了边界。
实作
这是完整的Xcode项目。使用Format顶部菜单项触发markTweet功能。
这是我将属性添加到段落的方法
@IBAction func markTweet(_ sender : Any?){
print("now we are marking")
let location = textView.selectedRange().location
guard let nsRange = textView.string.extractRange(by: .byParagraphs, at: location) else { print("Not in a paragraph"); return }
let substring = (textView.string as NSString).substring(with: nsRange)
let tweetParagraph = NSMutableParagraphStyle()
tweetParagraph.textBlocks = [TweetTextBlock()]
let twitterAttributes : [AttKey : Any] = [
AttKey.paragraphStyle : tweetParagraph,
AttKey.font : NSFont(name: "HelveticaNeue", size: …Run Code Online (Sandbox Code Playgroud) 在将现有应用程序转换为深色模式时,我偶然发现了一个UITextView带有 an的初始化NSAttributedString,用于为某些应用程序商店法律术语提供精美印刷。这在浅色模式下看起来不错,但在深色模式下我会在黑色上看到黑色文本。我提供默认前景色的第一个想法是添加以下内容:
import UIKit
let fgColor: UIColor
if #available(iOS 13.0, *) {
fgColor = .label
} else {
fgColor = .black
}
let s = try NSAttributedString(data: NSLocalizedString("""
<p style="text-align: center; font-size: smaller;">
Your payment will be charged to your iTunes Account at confirmation of purchase. Your subscription automatically renews unless auto-renew is turned off at least 24-hours before the end of the current period. Your Account will be charged for renewal within 24-hours prior to …Run Code Online (Sandbox Code Playgroud) 我有以下代码来尝试为标签的字符串添加下划线。
let attributedString = NSMutableAttributedString(string: "Hello World!")
attributedString.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single, range: NSRange.init(location: 0, length: attributedString.length))
label.attributedText = attributedString
Run Code Online (Sandbox Code Playgroud)
但是,运行代码时,标签显示Hello World!没有下划线。
我正在运行 Xcode 12.4,并使用 iOS 14.4 iPhone 12 Pro Max 模拟器。
ios ×8
swift ×5
objective-c ×4
uilabel ×3
html ×2
uitextview ×2
fonts ×1
iphone ×1
nstextview ×1
sklabelnode ×1
sprite-kit ×1
textkit ×1
uifont ×1
uikit ×1