Diego Charles
Diego Charles

Reputation: 113

Customizing UISegmentedControl border and Background on Xcode8 - Swift 3

I'm trying to customize the UISegmented Control's appearance as the follow image: enter image description here

Being more specifically, I'm having problems trying to drop this shadow, setting the height and also the background color.

Can you help me please?

Upvotes: 0

Views: 52

Answers (1)

Britto Thomas
Britto Thomas

Reputation: 2120

You can customise UISegmentController by sub classing it. Please see below code.

class SegmentController : UISegmentedControl {

 override func awakeFromNib() {
    self.layer.borderWidth = 0
    self.tintColor = UIColor.clear
    self.backgroundColor = UIColor.white
    let segAttributesSelected: NSDictionary = [
        NSAttributedStringKey.foregroundColor: UIColor.red,
        NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 15)
    ]
    let segAttributes: NSDictionary = [
        NSAttributedStringKey.foregroundColor: UIColor.lightGray,
        NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 15)
    ]
    self.setTitleTextAttributes(segAttributesSelected as [NSObject : AnyObject], for: UIControlState.selected)
    self.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.normal)
 }

 override func draw(_ rect: CGRect) {
    self.layer.shadowColor = UIColor.black.cgColor
    self.layer.shadowRadius = 2.0
    self.layer.shadowOffset = CGSize.init(width: 0, height: 0)
    self.layer.shadowOpacity = 1.0
    self.layer.backgroundColor = UIColor.white.cgColor
 }
}

Make suitable adjustment to constrains in storyboard to set height and position. Storyboard Screen short


Final output

enter image description here

Upvotes: 1

Related Questions