ios - 如何自定义 UISegmentedControl 以更改所选段的底部边框?

标签 ios swift border customization uisegmentedcontrol

我想自定义 UISegmentedControl,如下图:

enter image description here

最佳答案

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

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

    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!
}

关于ios - 如何自定义 UISegmentedControl 以更改所选段的底部边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399743/

相关文章:

ios - CoreMotion 姿态引用框架

jquery - 我可以在 Windows 中使用 (html & css & jquery) 构建 iPad 应用程序吗

ios - 添加到 coredata 数组时出现类型不匹配问题

html - 如何将周期性图像作为边框添加到 div

java - 如何在JFrame的边框上绘图

ios - UIPickerView 为空

ios - 如何子类化 UI 元素,如 UILabel、UIButton

swift - UIKit 碰撞检测和 Action

swift - swift 将 uint32 值拆分为 uint8 值

css - 覆盖 :hover 的伪标签上的边框