Maxwell Bo Blessen
Maxwell Bo Blessen

Reputation: 173

UISlider making it square not rounded

why does it do this? how can i change it? and is there anyway to change the slider so the progress slider is not rounded but square?

https://i.sstatic.net/MfNHo.jpg

I would prefer it to be square, the code is just a normal UI slider implementation. I only edited the

override func trackRectForBounds(bounds: CGRect) -> CGRect {
    return CGRectMake(0, 0, self.frame.width, 25)
}

to make the bar taller

Upvotes: 5

Views: 7513

Answers (3)

birdy
birdy

Reputation: 953

slider.setMaximumTrackImage(UIImage.imageWith(color: .yellow), for: .normal)
slider.setMinimumTrackImage(UIImage.imageWith(color: .cyan), for: .normal)

UIImage extension:

static func imageWith(color: UIColor, size: CGSize? = nil) -> UIImage? {
    let rect = CGRect(x: 0, y: 0, width: size?.width ?? 1, height: size?.height ?? 1)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()
    context?.setFillColor(color.cgColor)
    context?.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

Upvotes: 4

Zafar Ahmad
Zafar Ahmad

Reputation: 3219

Simple

slider.setMinimumTrackImage(getImageWithColor(color: .blue, size: slider.frame.size), for: .normal)

func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(rect)
    let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

Upvotes: 1

charlyatwork
charlyatwork

Reputation: 1197

You can set the minimum and maximum track image. Just use an image (rectangle without corner radius) with a width of 1px and height of 25px.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISlider_Class/#//apple_ref/doc/uid/TP40006798-CH3-SW21

Sample:

slider.setMinimumTrackImage(UIImage(named: "back"), forState: UIControlState.Normal)
slider.setMaximumTrackImage(UIImage(named: "back"), forState: UIControlState.Normal)

The back image is just a blue square image of size 25px.

Slider

The back Image: (just copy and paste) enter image description here

Upvotes: 9

Related Questions