更改UISegementControl的边框,字体和颜色

时间:2017-10-26 12:02:51

标签: ios ipad ios11 uisegmentedcontrol xcode9

我们如何更改UISegmentControl的以下属性:字体,边框,颜色。我需要UISegementControl如下所示:

enter image description here

用Google搜索了大约一个小时但未找到任何正确的答案。请指导。

以下是我到目前为止所尝试的内容:

override func viewDidLayoutSubviews() {

    self.segmentTimes = UISegmentedControl.appearance()
    self.segmentTimes.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.black], for: UIControlState.normal)
    self.segmentTimes.tintColor = UIColor.black



    let attr = NSDictionary(object: UIFont(name: "Sans-Regular", size: 14.0)!, forKey: NSFontAttributeName as NSCopying)
    self.segmentTimes.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
    self.segmentDuration.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
    self.segmentSeverity.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
    self.segmentCharacter.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
    self.segmentDurationType.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
}

我到目前为止管理的是:

enter image description here

1 个答案:

答案 0 :(得分:0)

请按如下方式创建自定义UIControl,适用于Swift 3 Xcode 8/9,并根据文字宽度调整分段创建宽度

import UIKit

@IBDesignable class RUISegmentedControl: UIControl {
fileprivate var labels = [UILabel]()
var thumbView = UIView()

var items: [String] = [] {
    didSet {
        setupLabels()
    }
}

var selectedIndex : Int = 0 {
    didSet {
        displayNewSelectedIndex()
    }
}

@IBInspectable var selectedLabelColor : UIColor = O2OStatics.color.RUISegmentedControlColor.selectedLabelColor {
    didSet {
        setSelectedColors()
    }
}

@IBInspectable var unselectedLabelColor : UIColor = O2OStatics.color.RUISegmentedControlColor.selectedLabelColor {
    didSet {
        setSelectedColors()
    }
}

@IBInspectable var thumbColor : UIColor = O2OStatics.color.RUISegmentedControlColor.thumbColor {
    didSet {
        setSelectedColors()
    }
}

@IBInspectable override var borderColor : UIColor? {
    didSet {
        layer.borderColor = borderColor?.cgColor
    }
}

@IBInspectable var font : UIFont! = UIFont.systemFont(ofSize: 12) {
    didSet {
        setFont()
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)

    setupView()
}

required init(coder: NSCoder) {
    super.init(coder: coder)!
    setupView()
}

func setupView(){

    layer.borderColor = UIColor(white: 1.0, alpha: 0.5).cgColor
    layer.borderWidth = 2

    backgroundColor = O2OStatics.color.RUISegmentedControlColor.backgroundColor

    setupLabels()

    addIndividualItemConstraints(labels, mainView: self, padding: 0)

    insertSubview(thumbView, at: 0)
}

func setupLabels(){

    for label in labels {
        label.removeFromSuperview()
    }

    labels.removeAll(keepingCapacity: true)

    for index in 1...items.count {

        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 70, height: 40))
        label.text = items[index - 1]
        label.backgroundColor = O2OStatics.color.RUISegmentedControlColor.labelBackgroundColor
        label.textAlignment = .center
        label.font = font
        label.textColor = index == 1 ? selectedLabelColor : unselectedLabelColor
        label.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(label)
        labels.append(label)
    }

    addIndividualItemConstraints(labels, mainView: self, padding: 0)
}

override func layoutSubviews() {
    super.layoutSubviews()

    var selectFrame = self.bounds
    let newWidth = selectFrame.width / CGFloat(items.count)
    selectFrame.size.width = newWidth
    thumbView.frame = selectFrame
    thumbView.backgroundColor = thumbColor
    thumbView.layer.cornerRadius = thumbView.frame.height / 10

    displayNewSelectedIndex()

}
override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
    let location = touch.location(in: self)

    var calculatedIndex : Int?
    for (index, item) in labels.enumerated() {
        if item.frame.contains(location) {
            calculatedIndex = index
        }
    }


    if calculatedIndex != nil {
        selectedIndex = calculatedIndex!
        sendActions(for: .valueChanged)
    }

    return false

}


func displayNewSelectedIndex(){
    for (_, item) in labels.enumerated() {
        item.textColor = unselectedLabelColor
    }

    let label = labels[selectedIndex]
    label.textColor = selectedLabelColor

    UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .curveEaseIn, animations: {

        self.thumbView.frame = label.frame

        }, completion: nil)
}

func addIndividualItemConstraints(_ items: [UIView], mainView: UIView, padding: CGFloat) {

    _ = mainView.constraints

    for (index, button) in items.enumerated() {

        let topConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: mainView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0)

        let bottomConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: mainView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0)

        var rightConstraint : NSLayoutConstraint!

        if index == items.count - 1 {

            rightConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: mainView, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: -padding)

        }else{

            let nextButton = items[index+1]
            rightConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: nextButton, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: -padding)
        }


        var leftConstraint : NSLayoutConstraint!

        if index == 0 {

            leftConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: mainView, attribute: NSLayoutAttribute.left, multiplier: 1.0, constant: padding)

        }else{

            let prevButton = items[index-1]
            leftConstraint = NSLayoutConstraint(item: button, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: prevButton, attribute: NSLayoutAttribute.right, multiplier: 1.0, constant: padding)

            let firstItem = items[0]

            let widthConstraint = NSLayoutConstraint(item: button, attribute: .width, relatedBy: NSLayoutRelation.equal, toItem: firstItem, attribute: .width, multiplier: 1.0  , constant: 0)

            mainView.addConstraint(widthConstraint)
        }

        mainView.addConstraints([topConstraint, bottomConstraint, rightConstraint, leftConstraint])
    }
}

func setSelectedColors(){
    for item in labels {
        item.textColor = unselectedLabelColor
    }

    if labels.count > 0 {
        labels[0].textColor = selectedLabelColor
    }

    thumbView.backgroundColor = thumbColor
}

func setFont(){
    for item in labels {
        item.font = font
    }
}
}