如何使用 Swift 仅设置选定段的文本色调?

How to Set tint color of text only of selected segment using Swift?

我使用了下面的代码来设置 UISegmentedControl 的背景。

homeSegment.setDividerImage(UIImage(named: "seperator.png"), forLeftSegmentState: UIControlState.Normal, rightSegmentState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)



homeSegment.setBackgroundImage(UIImage(named: "squareSegment.png"), forState: UIControlState.Selected, barMetrics: UIBarMetrics.Default)
homeSegment.setBackgroundImage(UIImage(named: "squareSegment.png"), forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)

如何设置所选段的文本颜色?

我使用 setTitleTextAttributes 完成了这个。下面的示例使用字典来设置属性,因为您很可能希望同时设置字体类型和大小。尝试将您选择的句段文本颜色设置为红色:

let segAttributes: NSDictionary = [
       NSForegroundColorAttributeName: UIColor.redColor(), 
                  NSFontAttributeName: UIFont(name: "Avenir-MediumOblique", size: 20)!
]

homeSegment.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], forState: UIControlState.Selected)

示例:

@Portland Runner 答案是针对旧版本的 Swift。

Swift 3.0,这有效。

逻辑与@Portland Runner相同,但语法根据Swift 3.0

修改和更新

这里我实现的这段代码是Segment控件的扩展,可以用于应用程序中的所有Segment控件,其中代码集必须在应用程序中定义class.

extension UISegmentedControl {
func setSegmentStyle() {
    setBackgroundImage(imageWithColor(color: backgroundColor!), for: .normal, barMetrics: .default)
    setBackgroundImage(imageWithColor(color: tintColor!), for: .selected, barMetrics: .default)
    setDividerImage(imageWithColor(color: UIColor.clear), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)



     let segAttributes: NSDictionary = [
            NSForegroundColorAttributeName: UIColor.gray,
            NSFontAttributeName: UIFont(name: "System-System", size: 14)!
        ]

        setTitleTextAttributes(segAttributes as [NSObject : AnyObject], for: UIControlState.selected)
    }

    // create a 1x1 image with this color
    private func imageWithColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0.0, y: 0.0, width:  1.0, height: 1.0)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor);
        context!.fill(rect);
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!
    }
}

可以在任何地方使用以下代码

 self.mySegment.setSegmentStyle()

对于Swift 4.0

let fontAttribute = [NSAttributedStringKey.font: UIFont(name: "Montserrat-Regular", size: 12)!, 
                       NSAttributedStringKey.foregroundColor: UIColor.red]

segmentedControl.setTitleTextAttributes(fontAttribute, for: .normal)