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

Saq*_*mer 8 uisegmentedcontrol ios 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)
Run Code Online (Sandbox Code Playgroud)

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

Por*_*ner 11

我通过使用来实现这一点setTitleTextAttributes.下面的示例使用字典来设置属性,因为您最有可能想要同时设置字体类型和大小.尝试将此选定的段文本颜色设置为红色:

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

homeSegment.setTitleTextAttributes(segAttributes as [NSObject : AnyObject], forState: UIControlState.Selected)
Run Code Online (Sandbox Code Playgroud)

例:

在此输入图像描述


小智 10

对于Swift 4.0

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

segmentedControl.setTitleTextAttributes(fontAttribute, for: .normal)
Run Code Online (Sandbox Code Playgroud)