App运行崩溃报'unrecognized selector sent to instance 0x6000001e1a40'错误,且UISegmentedControl选中项下划线设置函数异常求助
解决UISegmentedControl下划线样式崩溃与逻辑问题
首先来说说导致你App崩溃的核心原因:你在设置NSAttributedString.Key.foregroundColor时传入了UIColor.white.cgColor,但这个属性要求的是UIColor实例,而非CGColor。系统解析属性时,会尝试对CGColor对象执行UIColor相关的方法,自然就抛出了unrecognized selector sent to instance错误。
再看下划线效果的逻辑问题:你的代码重复判断每个索引的选中状态,且每次只设置单一状态的属性,容易导致样式覆盖不完整。其实UISegmentedControl会自动根据选中状态应用对应文本属性,我们只需要一次性设置好.selected和.normal两种状态的样式即可,不需要逐个索引判断。
下面是修正后的完整代码:
func setupSegmentControlStyle() { guard let font = UIFont(name: "DIN Condensed Bold", size: 20.0) else { print("无法加载指定字体") return } // 选中状态:带白色下划线的文本样式 let selectedTextAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.white, .underlineStyle: NSUnderlineStyle.single.rawValue, .font: font ] // 未选中状态:无下划线的文本样式 let normalTextAttributes: [NSAttributedString.Key: Any] = [ .foregroundColor: UIColor.white, .font: font ] // 为分段控件统一设置两种状态的样式 seasonsAndPointSegment.setTitleTextAttributes(selectedTextAttributes, for: .selected) seasonsAndPointSegment.setTitleTextAttributes(normalTextAttributes, for: .normal) }
补充使用说明:
- 建议在
viewDidLoad()中调用这个方法,完成分段控件的样式初始化; - 如果需要在用户切换分段时联动刷新TableView,给
seasonsAndPointSegment添加valueChanged事件监听即可,样式无需重复设置; - 若想区分选中/未选中的文字颜色,只需修改
normalTextAttributes里的.foregroundColor值(比如改成浅灰色)。
内容的提问来源于stack exchange,提问作者iFateh
相关产品推荐
相关产品推荐

