我有一个带有两个段的简单 UISegmentedControl
,我正在尝试自定义它的外观。
我收到这个运行时错误:
*** Terminating app due to uncaught exception >'NSInvalidArgumentException', reason: '-[NSNull renderingMode]: unrecognized selector sent to instance 0x112156f08'
@IBOutlet weak var sortController: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
styleSortController()
// other setup code
}
func styleSortController() {
let titleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0)) as Any]
let selectedTitleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]
// this line causes it to crash
sortController.setTitleTextAttributes(titleAttributes, for: UIControlState.normal)
// but this line works, no problem
sortController.setTitleTextAttributes(selectedTitleAttributes, for: UIControlState.selected)
}
由上面看到的行引起,我首先尝试设置标题文本属性(请注意,第二行设置属性工作正常)。
根据 Apple 的文档,我应该能够使用任何有效的 UIControlState
并且 UIControlState.normal
确实看起来有效,所以我真的很困惑为什么会这样。
这条线会给我带来什么麻烦?
最佳答案
let titleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0)) as Any]
let selectedTitleAttributes: [String: Any] = [NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "AvenirNext-DemiBold", size: CGFloat(14.0)) as Any]
在说是UIControlState
问题之前,你需要做:
sortController.setTitleTextAttributes(selectedTitleAttributes, for: UIControlState.normal)
换句话说,使用相同的工作示例(.selected
的示例)
它应该会造成同样的错误崩溃。
然后你会发现罪魁祸首是UIFont(name: "AvenirNext-Demi", size: CGFloat(14.0))
,它返回nil。
因此字体名称无效。
您可以遍历您的字体以列出它 ( see this related question ) 并找到正确的字体。 这是一个“普通的”,所以你可以打开 Font Book.app,找到它,然后检查它的 Post script 名称。并非 macOS 中的所有字体都在 iOS 中,但 iOS 就是这种情况。
您将获得:AvenirNext-Regular、AvenirNext-Medium、AvenirNext-UltraLight、AvenirNext-Italic>、AvenirNext-MediumItalic、AvenirNext-UltraLightItalic、AvenirNext-DemiBold、AvenirNext-Bold、AvenirNext -重,AvenirNext-DemiBoldItalic,AvenirNext-BoldItalic,AvenirNext-HeavyItalic。
没有 AvenirNext-Demi。
因此,请使用您认为更适合您的需求。
如果您使用自定义字体,我建议您在 Mac 中安装它们。这样很容易检查字体的后记名称。
关于swift - 为什么在分段控件上使用 UIControlState.normal 会导致此崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085198/