【问题标题】:how to set attributes in NSAttributedString in iOS?如何在 iOS 的 NSAttributedString 中设置属性?
【发布时间】:2012-07-11 21:41:53
【问题描述】:

我正在尝试在 iOS 中设置 NSAttributedString 的臭名昭著的 NSFontAttributeName 属性,但它似乎不起作用:

  1. 首先,似乎没有为 iOS 定义任何 NS 常量
  2. 我在某处读到,我可以通过传递来解决它 CoreText consts 代替。很好......但仍然,属性 需要一个 NSFont,我被 UIFont 或 CTFontRef 困住,两者都不是 这似乎有效:

这不起作用:

CTFontRef ctFont = CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:16].fontName, [UIFont boldSystemFontOfSize:16].pointSize, NULL);
[myAttString addAttribute:(NSString*)kCTFontNameAttribute
                          value:(id)ctFont
                          range:NSMakeRange(0, myAttString.length-1)];

这不起作用:

[myAttString addAttribute:(NSString*)kCTFontNameAttribute
                          value:[UIFont boldSystemFontOfSize:16]
                          range:NSMakeRange(0, myAttString.length-1)];

有没有办法让这个工作?

【问题讨论】:

    标签: ios cocoa-touch core-text nsattributedstring


    【解决方案1】:

    我找到了!

    基本上,我应该使用的字典键的字符串常量是 kCTFontAttributeName

    这整件事就是一场表演......

    【讨论】:

      【解决方案2】:

      NS 常量和完整的属性字符串支持将在那里。不过,iOS5 中还没有。

      CoreText 常量确实有效,CTFontRef 也是我使用它的方式。您的代码的第一块应该可以工作。你能验证你的其他代码,问题不在其他地方吗?

      【讨论】:

      • 好吧,我的整个代码完全按照我所展示的...然后将属性字符串设置为 CATextLayer 的字符串。但至少在屏幕上显示 CALayer 时,字体属性似乎没有生效。我也尝试设置颜色属性而不是字体名称,以防它与 CA 相关.. 但该属性例如生效就好了..
      • 我什至尝试对字体进行硬编码,如下所示:'CTFontRef ctFont = CTFontCreateWithName((CFStringRef)@"Helvetica-Bold", 20, NULL);'还是什么都没有
      【解决方案3】:

      这样做:

      let paragraphStyle = NSMutableParagraphStyle()
      paragraphStyle.alignment = .center
      
      
      let attributes = [NSParagraphStyleAttributeName :  paragraphStyle,
                        NSFontAttributeName :   UIFont.systemFont(ofSize: 24.0),
                        NSForegroundColorAttributeName : UIColor.blue,
                        ]
      
      let attrString = NSAttributedString(string: "Stop\nall Dance",
                                     attributes: attributes)
      

      【讨论】:

        猜你喜欢
        • 2021-07-22
        • 1970-01-01
        • 2011-10-06
        • 1970-01-01
        • 1970-01-01
        • 2012-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多