Skip to content

Instantly share code, notes, and snippets.

@Denismih
Created April 24, 2019 11:25
Show Gist options
  • Save Denismih/e380d2d342e9b835209fbeb1f6c738c8 to your computer and use it in GitHub Desktop.
Save Denismih/e380d2d342e9b835209fbeb1f6c738c8 to your computer and use it in GitHub Desktop.
extension UISegmentedControl {
func removeBorder(){
self.tintColor = UIColor.clear
self.backgroundColor = UIColor.clear
self.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor : UIColor.stavkrugDarkBlue], for: .selected)
self.setTitleTextAttributes( [NSAttributedString.Key.foregroundColor : UIColor.gray], for: .normal)
}
func setupSegment() {
self.removeBorder()
let segmentUnderlineWidth: CGFloat = self.bounds.width
let segmentUnderlineHeight: CGFloat = 2.0
let segmentUnderlineXPosition = self.bounds.minX
let segmentUnderLineYPosition = self.bounds.size.height - 1.0
let segmentUnderlineFrame = CGRect(x: segmentUnderlineXPosition, y: segmentUnderLineYPosition, width: segmentUnderlineWidth, height: segmentUnderlineHeight)
let segmentUnderline = UIView(frame: segmentUnderlineFrame)
segmentUnderline.backgroundColor = UIColor.clear
self.addSubview(segmentUnderline)
self.addUnderlineForSelectedSegment()
}
func addUnderlineForSelectedSegment(){
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 = UIColor.stavkrugDarkBlue
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)
underline.frame.origin.x = underlineFinalXPosition
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment