UISlider使它成为方形而不是圆形

时间:2015-07-15 21:47:29

标签: swift uislider

为什么这样做?我怎么能改变它?无论如何都要更改滑块以使进度滑块不是圆角而是方形?

http://imgur.com/F9Ye24v

我希望它是正方形,代码只是一个普通的UI滑块实现。我只编辑了

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

让酒吧更高

3 个答案:

答案 0 :(得分:8)

您可以设置最小和最大曲目图像。 只需使用宽度为1像素,高度为25像素的图像(没有角半径的矩形)。

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

样品:

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

back图像只是一张大小为25像素的蓝色方形图像。

Slider

背面图片:(只需复制并粘贴) enter image description here

答案 1 :(得分:0)

简单

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
}

答案 2 :(得分:-1)

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

UIImage扩展名:

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
}