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

时间:2015-02-13 10:33:04

标签: ios swift uisegmentedcontrol

我使用以下代码来设置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)

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

3 个答案:

答案 0 :(得分:10)

我使用setTitleTextAttributes完成此操作。下面的示例使用字典来设置属性,因为您最有可能想要同时设置字体类型和大小。尝试将此选定的段文本颜色设置为红色:

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

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

示例:

enter image description here

答案 1 :(得分:9)

Swift 4.0

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

segmentedControl.setTitleTextAttributes(fontAttribute, for: .normal)

答案 2 :(得分:1)

@Portland Runner答案适用于旧版Swift。

Swift 3.0,这可行。

逻辑与@Portland Runner相同,但语法根据Swift 3.0修改和更新

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

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()

enter image description here