我有一个CustomSegmentedControl
类,它将下划线应用于当前选定的细分。它会将此下划线创建为白色UIView
并且工作正常(包含动画)但下划线显示在段后面,因此无法看到。我无法弄清楚幕后发生的事情,我们非常感谢任何提示。
import UIKit
class CustomSegmentedControl: UISegmentedControl {
override func awakeFromNib() {
super.awakeFromNib()
}
func removeBorder() {
let backgroundImage = UIImage.getColoredRectImageWith(color: JSColors.Orange.main.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 dividerImage = UIImage.getColoredRectImageWith(color: JSColors.Orange.main.cgColor, andSize: CGSize(width: 1.0, height: self.bounds.size.height))
self.setDividerImage(dividerImage, forLeftSegmentState: .selected, rightSegmentState: .normal, barMetrics: .default)
self.setTitleTextAttributes([
NSAttributedStringKey.font : Font.Roboto.header,
NSAttributedStringKey.foregroundColor: UIColor.white.withAlphaComponent(0.5)
], for: .normal)
self.setTitleTextAttributes([
NSAttributedStringKey.font : Font.Roboto.header,
NSAttributedStringKey.foregroundColor: UIColor.white
], for: .selected)
}
func addUnderlineForSelectedSegment() {
removeBorder()
let underlineWidth: CGFloat = self.bounds.size.width / CGFloat(self.numberOfSegments) - 20.0
let underlineHeight: CGFloat = 2.0
let underlineXPosition = CGFloat(selectedSegmentIndex * Int(underlineWidth)) + 10.0
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 = .white
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) + 10.0
UIView.animate(withDuration: 0.1, animations: {
underline.frame.origin.x = underlineFinalXPosition
self.bringSubview(toFront: underline)
})
}
}
extension UIImage {
class func getColoredRectImageWith(color: CGColor, andSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let graphicsContext = UIGraphicsGetCurrentContext()
graphicsContext?.setFillColor(color)
let rectangle = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
graphicsContext?.fill(rectangle)
let rectangleImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rectangleImage!
}
}