设置UIControl子类的selectedTitleTextAttributes

时间:2018-07-10 21:28:02

标签: swift

我正在使用一个名为HMSegmentedControl的分段控制库,它不太复杂,但是设置其titleTextAttributes给我带来了一些麻烦。

titleTextAttributes通过Swift键入[AnyHashable: Any]!。在objc文件中,它是@property (nonatomic, strong) NSDictionary *titleTextAttributes

这就是我在做什么:

let segmentedControl = HMSegmentedControl(sectionTitles: ["All", "A", "B"])!
segmentedControl.titleTextAttributes = [
      NSFontAttributeName: Styleguide.Fonts.someFont.font(ofSize: 9),
      NSForegroundColorAttributeName: UIColor.lightGray
]

Xcode给我NSFontAttributeNameNSForegroundColorAttributeName的“使用无法解析的标识符”错误

1 个答案:

答案 0 :(得分:1)

好吧,因为它们是Obj-C标识符。您应该使用Swift的:

NSAttributedStringKey.font(或者通常只是.font,在处理本机对象时,swift可以推断出其余部分,尽管在这种情况下,如果声明为AnyHashable: Any,则可能不会) 和NSAttributedStringKey.foregroundColor

所以您想要的是:

segmentedControl.titleTextAttributes = [
      NSAttributedStringKey.font: Styleguide.Fonts.someFont.font(ofSize: 9),
      NSAttributedStringKey.foregroundColor: UIColor.lightGray
]