简体   繁体   English

如何在 Swift 4 中为 UISlider 轨道添加边框颜色?

[英]How to add border color to UISlider track in Swift 4?

I want to make UISlider with minimumTrackTintColor and minimumTrackTintColor with track borderColor我想用UISliderminimumTrackTintColor轨道minimumTrackTintColor制作borderColor

I've already set a trackTintColor for both minimum and maximum state but instead I want to add border for UISlider track我已经为minimummaximum state 设置了trackTintColor但我想为UISlider轨道添加边框

  • My UISlider looks Like this:我的UISlider看起来像这样:

滑块图像 1 滑块图像 2

  • I need to track border like this:我需要像这样跟踪边界:

带边框的图像

  • Code代码

class SliderWithHeart: UISlider
{

    override func awakeFromNib()
    {
        super.awakeFromNib()

        let imageTint = UIImage(named: "SliderHeart")
        self.minimumTrackTintColor = colorWithHex(hex: COLORCODE.APP_BUTTON_COLOR)
        self.maximumTrackTintColor = colorWithHex(hex: COLORCODE.APP_ORANGE_COLOR)
        self.setThumbImage(imageTint, for: .normal)
    }
    override func layoutSubviews()
    {
        super.layoutSubviews()
        super.layer.cornerRadius = self.frame.height/2
    }

    override func trackRect(forBounds bounds: CGRect) -> CGRect
    {
        var newBounds = super.trackRect(forBounds: bounds)
        newBounds.size.height = 10
        return newBounds
    }

}

How do I set the border color of the slider track, not the entire slider?如何设置 slider 轨道的边框颜色,而不是整个 slider?

You can get the super-view of UISlider to do the modifications as per the requirements.您可以获取UISlider的超级视图以根据要求进行修改。

To increase the height:要增加高度:

 class CustomSlider: UISlider {

   override func trackRect(forBounds bounds: CGRect) -> CGRect {
       let customBounds = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width, height: 17.0))
       super.trackRect(forBounds: customBounds)
       return customBounds
   }
}

To add the border (you can write this code in the viewDidLoad() method):添加边框(您可以在viewDidLoad()方法中编写此代码):

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            if #available(iOS 14.0, *) {
                self.slider.subviews.first?.subviews[1].layer.borderWidth = 2.8
                self.slider.subviews.first?.subviews[1].layer.borderColor = UIColor.white.cgColor
                self.slider.subviews.first?.subviews[1].makeRoundCorner(8.0)
            }
            else{
                self.slider.subviews[1].layer.borderWidth = 2.8
                self.slider.subviews[1].layer.borderColor = UIColor.white.cgColor
                self.slider.subviews[1].makeRoundCorner(8.0)
            }
        }

I had to use the delay to get it initialized.我不得不使用延迟来初始化它。

Result:结果:

在此处输入图像描述

Note: I didn't provide the code for the thumb, shadow, and other properties of the slider.注意:我没有提供滑块的拇指、阴影和其他属性的代码。

I guess the best option is to add a border layer to Track CGRect.我想最好的选择是为 Track CGRect 添加一个边框层。

Find below a UISlider subclassing approach in Swift 5:在 Swift 5 中找到下面的 UISlider 子类化方法:


final class BorderedUISlider: UISlider {
    private var sliderBorder: CALayer = {
        let layer = CALayer()
        layer.borderWidth = 1
        layer.borderColor = ***Here Your Color***.cgColor
        return layer
    }()
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let rect = trackRect(forBounds: bounds)
        sliderBorder.removeFromSuperlayer()
        sliderBorder.frame = rect
        sliderBorder.cornerRadius = rect.height / 2
        layer.addSublayer(sliderBorder)
    }
}

If you debug UISlider on view hierarchy, you will see the boundaries of the slider.如果您在视图层次结构上调试 UISlider,您将看到 slider 的边界。

在视图层次结构中选择的滑块 视图层次结构上滑块的边界

According to this, you can set the backgroundColor of the slider to add a border effect (default is nil ).据此,可以设置 slider 的backgroundColor来添加边框效果(默认为nil )。

Example:例子:

let valueSlider: UISlider = {
    let slider = UISlider(frame: .zero)
    slider.translatesAutoresizingMaskIntoConstraints = false
    slider.isContinuous = true
    slider.tintColor = .green
    slider.thumbTintColor = .darkGray
    slider.cornerRadius = 4
    slider.clipsToBounds = false
    slider.maximumTrackTintColor = .gray

    // Setting the background will add the effect of a border for the slider
    slider.backgroundColor = .gray

    return slider
}()

Without setting backgroundColor:不设置背景颜色: 在此处输入图像描述

With backgroundColor:带背景颜色: 在此处输入图像描述

在此处输入图像描述

The above figure is an example, using pure code implementation.上图是一个例子,使用纯代码实现。

  private let volumeSlider = UISlider().then {
    let minimumTrackImage = UIView().then {
      $0.backgroundColor = R.color.tint()
      $0.pin.size(CGSize(width: 312, height: 6)) // <<< Key location, width of your slider, you can also customize the height here.
      $0.cornerRadius = 3
    }.screenshot

    let maximumTrackImage = UIView().then {
      $0.backgroundColor = .white
      $0.pin.size(CGSize(width: 312, height: 6))
      $0.borderColor = R.color.tint()
      $0.borderWidth = 1
      $0.cornerRadius = 3
    }.screenshot

    let thumbImage = UIView().then {
      $0.backgroundColor = .white
      $0.cornerRadius = 13
      $0.pin.size($0.cornerRadius * 2)
      $0.borderColor = R.color.tint()
      $0.borderWidth = 1
    }.screenshot

    $0.setMinimumTrackImage(minimumTrackImage, for: .normal)
    $0.setMaximumTrackImage(maximumTrackImage, for: .normal)
    $0.setThumbImage(thumbImage, for: .normal)
    $0.value = 0.3
  }

The code is from my project, using a bunch of third-party libraries, but I think it should not prevent you from understanding it.代码来自我的项目,使用了一堆第三方库,但我认为它不应该妨碍你理解它。 They are all helpers and will not affect the core code.它们都是助手,不会影响核心代码。

Which:哪个:
- R is from R.Swift . - R来自R.Swift
- then is from Then . - then来自Then
- pin is from PinLayout . - pin来自PinLayout
- screenshot is - screenshot

extension UIView {

  var screenshot: UIImage {
    return UIGraphicsImageRenderer(size: bounds.size).image { _ in
      drawHierarchy(in: bounds, afterScreenUpdates: true)
    }
  }

}

You can also use images.您也可以使用图像。 As long as the width is the same as the maximum width of the slider.只要宽度与滑块的最大宽度相同。 Hope it helps you, although it is a little late.希望对你有所帮助,虽然有点晚了。 Any questions can be commented below.有什么问题可以在下方评论。

Add the border width and border color to your UISlider将边框宽度和边框颜色添加到 UISlider

Yourslider.layer.borderWidth = 4.0
let red = UIColor(red: 255.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
Yourslider.layer.borderColor = red.cgColor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM