swift - 为 UIControl 子类设置 selectedTitleTextAttributes

标签 swift

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

titleTextAttributes 是类型 [AnyHashable: Any]! 通过 Swift。在 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 提供了“使用未解析的标识符”错误

最佳答案

嗯,这是因为那些是 Obj-C 标识符。你应该使用 Swift 的:

NSAttributedStringKey.font(或者通常只是简单的 .font,swift 可以在处理本地对象时推断出其余部分,也许在这种情况下不会,但如果它被声明为 AnyHashable: 任何) 和 NSAttributedStringKey.foregroundColor

所以你想要的是:

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

关于swift - 为 UIControl 子类设置 selectedTitleTextAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51274140/

相关文章:

ios - 将数据从 UITableView 单元格传输到另一个 VC 的 tableview? ( swift )

在 NavigationController 中查看的 iOS 无效矩形

ios - 如何删除 iOS TableView 分隔符

ios - 完全删除 View Controller - Swift

ios - Xcode 11 iPad Storyboard不是全屏。这是一些新的行为或错误吗?

iphone - 同一个 ViewController 的 2 个 View

ios - AVAudioEngine.connect 上的 CoreAudio 错误和崩溃

ios - 如果没有互联网,请更改 ViewController

ios - 即使我使用 CocoaPods,我也需要安装 CoreData.framework 吗?

ios - 如何快速更改搜索栏的高度