如何在UITextView中水平居中放置一行文本? [英] How can I horizontally center a single line of text in UITextView?
问题描述
我有一个UITextView,它显示大量文本。我需要在文本视图中水平对齐部分(而不是全部)文本行。
I have a UITextView which displays a fair amount of text. I need to horizontally center some, but not all, of the lines of text in the text view.
我尝试将 NSParagraphStyleAttributeName
设置为其 alignment $的NSParagraphStyle实例。 c $ c>属性为
NSTextAlignmentCenter
在要居中的行范围内。我还设置了字体,使中心线为粗体。当我使用下面的代码执行此操作时,相关行以粗体显示,但保持左对齐。
I've tried setting the NSParagraphStyleAttributeName
with an NSParagraphStyle instance whose alignment
property is NSTextAlignmentCenter
on the range of the line to be centered. I'm also setting the font so the centered line is bold. When I do this using the code below, the relevant line is bolded, but remains left aligned.
if (shouldCenterLine) {
NSMutableParagraphStyle *centerStyle = [[NSMutableParagraphStyle alloc] init];
centerStyle.alignment = NSTextAlignmentCenter;
NSDictionary *attributes = @{NSParagraphStyleAttributeName : centerStyle,
NSFontAttributeName : boldFont};
[attributedString setAttributes:attributes range:lineRange];
}
如果我将同一段落样式属性应用于文本视图的全部内容,文本最终会按预期居中。
If I apply this same paragraph style attribute to the entire contents of the text view, the text ends up centered as expected.
是否有可能说服 UITextView
将其文本的特定子范围居中?迁移到 UIWebView
渲染生成的HTML的唯一解决方案是吗?请注意,这是针对仍支持iOS 6的应用程序,因此很遗憾,我无法使用文本工具包。
Is it possible to convince UITextView
to center specific subranges of its text? Is the only solution to move to a UIWebView
rendering generated HTML? Note that this is for an app still supporting iOS 6, so unfortunately I'm not able to use Text Kit.
推荐答案
尝试包括该行在内,将返回您希望应用的样式范围内的那条线的中心。
Try including the line returns around the the line that you'd like centered within the range that you apply the style to.
这篇关于如何在UITextView中水平居中放置一行文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!