【发布时间】:2018-08-10 19:12:15
【问题描述】:
我正在尝试为一个应用创建 2 个主题 - 浅色和深色。
在它们之间切换时,UISegmentedControl 不会被更改。它保持原始状态。不知道为什么。我确定我错过了什么或做错了什么,我只是不知道是什么。
class DiscoverVC: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
segmentedControl.addUnderlineForSelectedSegment()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
applyTheme()
}
}
extension DiscoverVC {
fileprivate func applyTheme() {
segmentedControl.tintColor = Theme.current.tint
}
}
extension UISegmentedControl{
func removeBorder() {
let backgroundImage = UIImage.getColoredRectImageWith(color: UIColor.clear.cgColor, andSize: self.bounds.size)
self.setBackgroundImage(backgroundImage, for: .normal, barMetrics: .default)
self.setBackgroundImage(backgroundImage, for: .selected, barMetrics: .default)
self.setBackgroundImage(backgroundImage, for: .highlighted, barMetrics: .default)
let deviderImage = UIImage.getColoredRectImageWith(color: UIColor.clear.cgColor, andSize: CGSize(width: 1.0, height: self.bounds.size.height))
self.setDividerImage(deviderImage, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
self.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: Theme.current.segmentedControl_unselectedColor, NSAttributedStringKey.font: UIFont(name: Fonts.OpenSans_Regular, size: 13)!], for: .normal)
self.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: Theme.current.segmentedControl_tintColor, NSAttributedStringKey.font: UIFont(name: Fonts.OpenSans_Bold, size: 13)!], for: .selected)
}
func addUnderlineForSelectedSegment() {
removeBorder()
let underlineWidth: CGFloat = self.bounds.size.width / CGFloat(self.numberOfSegments)
let underlineHeight: CGFloat = 2.0
let underlineXPosition = CGFloat(selectedSegmentIndex * Int(underlineWidth))
let underLineYPosition = self.bounds.size.height - 1.0
let underlineFrame = CGRect(x: underlineXPosition, y: underLineYPosition, width: underlineWidth, height: underlineHeight)
let underline = UIView(frame: underlineFrame)
underline.backgroundColor = Theme.current.segmentedControl_tintColor
underline.tag = 1
self.addSubview(underline)
}
func changeUnderlinePosition() {
guard let underline = self.viewWithTag(1) else {return}
let underlineFinalXPosition = (self.bounds.width / CGFloat(self.numberOfSegments)) * CGFloat(selectedSegmentIndex)
UIView.animate(withDuration: 0.1, animations: {
underline.frame.origin.x = underlineFinalXPosition
})
}
}
【问题讨论】:
标签: ios swift uisegmentedcontrol