NSAttributedString 添加文本对齐方式
如何向 NSAttributedString 添加文本对齐属性以使文本居中?
编辑: 我做错了什么吗?看起来并没有改变对齐方式。
CTParagraphStyleSetting setting;
setting.spec = kCTParagraphStyleSpecifierAlignment;
setting.valueSize = kCTCenterTextAlignment;
CTParagraphStyleSetting settings[1] = {
{kCTParagraphStyleSpecifierAlignment, sizeof(CGFloat), &setting},
};
CTParagraphStyleRef paragraph = CTParagraphStyleCreate(settings, sizeof(setting));
NSMutableAttributedString *mutableAttributed = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedString];
[mutableAttributed addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)paragraph ,(NSString*) kCTParagraphStyleAttributeName, nil] range:_selectedRange];
How can I add text alignment attribute to an NSAttributedString to center the text?
Edit:
Am I doing anything wrong? It doesn't seem to change the alignment.
CTParagraphStyleSetting setting;
setting.spec = kCTParagraphStyleSpecifierAlignment;
setting.valueSize = kCTCenterTextAlignment;
CTParagraphStyleSetting settings[1] = {
{kCTParagraphStyleSpecifierAlignment, sizeof(CGFloat), &setting},
};
CTParagraphStyleRef paragraph = CTParagraphStyleCreate(settings, sizeof(setting));
NSMutableAttributedString *mutableAttributed = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedString];
[mutableAttributed addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:(NSObject*)paragraph ,(NSString*) kCTParagraphStyleAttributeName, nil] range:_selectedRange];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
斯威夫特4.2
Swift 4.2
我正在寻找同样的问题,并且能够以这种方式将 NSAttributedString 中的文本居中对齐:
I was searching for the same issue and was able to center align the text in a NSAttributedString this way:
Swift 4.0+
Swift 3.0+
(原始答案如下)
Swift 2.0+
Swift 4.0+
Swift 3.0+
(original answer below)
Swift 2.0+
由于
NSAttributedString
主要与 iOS 上的 Core Text 一起使用,因此您必须使用CTParagraphStyle
而不是NSParagraphStyle
。没有可变的变体。例如:
As
NSAttributedString
is primarily used with Core Text on iOS, you have to useCTParagraphStyle
instead ofNSParagraphStyle
. There is no mutable variant.For example:
Swift 4 答案:
Swift 4 answer:
在快速4中:
In swift 4:
如果您使用
UILabel
,只需使用label.textAlignment = .center
即可If you use
UILabel
, just uselabel.textAlignment = .center
insteadXamarin.iOS
Xamarin.iOS