本文介绍了如何自定义UISegmentedControl更改选定的段底部边框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要自定义UISegmentedControl,如下图所示:

I want to customize UISegmentedControl like this image:

推荐答案

与此一起使用扩展名self.segmentController.customizeAppearance(for:1)

Use extension with thisself.segmentController.customizeAppearance(for: 1)

调用addBorder方法并将UISegmentedControl作为参数传递

Call addBorder method and pass your UISegmentedControl as a parameter

    static func addBorder(_ uiSegmentControl: UISegmentedControl){

    var upperBorder: CALayer = CALayer()
    upperBorder.backgroundColor = UIColor.init(red: 255.0, green:255.0, blue: 255.0, alpha: 1.0).cgColor
    upperBorder.frame = CGRect(x: 0, y: Int(ceil(uiSegmentControl.subviews[0].bounds.height))-1, width: Int(floor(uiSegmentControl.bounds.width)), height: 1)
    uiSegmentControl.layer.addSublayer(upperBorder)

    for i in 0..<uiSegmentControl.subviews.count {

        if i == uiSegmentControl.selectedSegmentIndex {
            upperBorder = CALayer()
            upperBorder.backgroundColor = UIColor.init(red: 215/255.0, green: 0.0, blue: 30/255.0, alpha: 1.0).cgColor
            upperBorder.frame = CGRect(x: i*Int(ceil(uiSegmentControl.subviews[i].bounds.width)), y: Int(ceil(uiSegmentControl.subviews[i].bounds.height))-1, width: Int(floor(uiSegmentControl.subviews[i].bounds.width)), height: 1)
            uiSegmentControl.layer.addSublayer(upperBorder)
        }
    }

}

extension UISegmentedControl {
func customizeAppearance(for height: Int) {
    setDividerImage(UIImage().colored(with: .clear, size: CGSize(width: 1, height: height)), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
    setBackgroundImage(UIImage().colored(with: .clear, size: CGSize(width: 1, height: height)), for: .normal, barMetrics: .default)
  }
}
extension UIImage {
    func colored(with color: UIColor, size: CGSize) -> UIImage {
    UIGraphicsBeginImageContext(size)
    let context = UIGraphicsGetCurrentContext()
    context!.setFillColor(color.cgColor);
    let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
    context!.fill(rect);
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image!
}

这篇关于如何自定义UISegmentedControl更改选定的段底部边框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:33