问题描述
我在 swift 编写的 iOS 应用中有多个 UI 段控件。
在 iOS 设备上进行模拟时,在初始加载时,它们使用代码中设置的正确自定义字体,但在某些情况下,我转到其他视图并返回时,段控制选项卡中的字体似乎恢复为系统字体自动。
是什么导致了这个问题?
我正在每个视图控制器中使用此功能创建所有分段控件。这是设置自定义字体的地方。
override func viewDidLoad() {
super.viewDidLoad()
isHirer = AppSettings.boolValue(.isHirer)
setupUI()
setupSegmentControl()
downloadData()
configureLocationManager()
}
func setupSegmentControl() {
var items = [String]()
items = AppSettings.boolValue(.isHirer) ? ["Posts","Manage"] : ["Search","Manage"]
let segmentedControl = UISegmentedControl(items: items)
segmentedControl.selectedSegmentIndex = 0
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(displayP3Red: 0/255,green: 0/255,blue: 0/255,alpha: 1),NSAttributedString.Key.font : UIFont.init(name: "Cabin-SemiBold",size: 16)!],for: .selected)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(displayP3Red: 138/255,green: 145/255,blue: 172/255,alpha: 0.7),for: .normal)
segmentedControl.frame = CGRect.init(x: 0,y: 42,width: tableView.frame.width/2-20,height: 48)
if AppSettings.boolValue(.isHirer) {
segmentedControl.setContentOffset(CGSize(width: 0,height: -5),forSegmentAt: 0)
segmentedControl.setContentOffset(CGSize(width: 0,forSegmentAt: 1)
} else {
segmentedControl.setContentOffset(CGSize(width: 5,forSegmentAt: 1)
}
segmentedControl.setBackgroundImage(backgroundWithColor(color: .backgroundGray,frame: CGRect(x: 0,y: 0,width: segmentedControl.frame.width,height: segmentedControl.frame.height)),for: .normal,barMetrics: .default)
segmentedControl.setDividerImage(imageWithColor(color: UIColor.white),forLeftSegmentState: .normal,rightSegmentState: .normal,barMetrics: .default)
segmentedControl.addTarget(self,action: #selector(showSection),for: .valueChanged)
seg = segmentedControl
}
@objc func showSection(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
isSegment0 = true
tableView.reloadData()
case 1:
isSegment0 = false
tableView.reloadData()
default:
break
}
}
然后在表视图的 ViewForHeaderInSection 函数中将 seg 添加到标题视图中。
override func tableView(_ tableView: UITableView,viewForHeaderInSection section: Int) -> UIView? {
if section == 0 && AppSettings.boolValue(.isHirer) || section == 0 && !AppSettings.boolValue(.isHirer) {
let headerView = UIView(frame: CGRect(x: 0,width: tableView.frame.width,height: 90))
headerView.backgroundColor = .backgroundGray
let segmentControl = seg
segmentControl.tag = section
headerView.addSubview(segmentControl)
return headerView
解决方法
请尝试如下修改您的代码:
之前:
UISegmentedControl.appearance().setTitleTextAttributes(...)
之后:
segmentedControl.setTitleTextAttributes(...)
即不要在 UISegmentedControl
类上使用外观代理
外观代理通常会在应用生命周期的早期在该类的任何控件被实例化之前完成一次。例如,您可以改用 AppDelegates didFinishLaunching()
API 中的外观代理,这样就无需在代码的其他地方调用 setTitleTextAttributes()
。
如果有帮助,请反馈。