有人能告诉我如何改变UISegmentedControl的字体类型和大小吗?


当前回答

这里我已经更新了iOS8

[[UISegmentedControl appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"STHeitiSC-Medium" size:13.0], NSFontAttributeName, nil] forState:UIControlStateNormal];

其他回答

UISegmentedControl的扩展,用于设置字体大小。

extension UISegmentedControl {
    @available(iOS 8.2, *)
    func setFontSize(fontSize: CGFloat) {
            let normalTextAttributes: [NSObject : AnyObject]!
            if #available(iOS 9.0, *) {
                normalTextAttributes = [
                    NSFontAttributeName: UIFont.monospacedDigitSystemFontOfSize(fontSize, weight: UIFontWeightRegular)
                ]
            } else {
                normalTextAttributes = [
                    NSFontAttributeName: UIFont.systemFontOfSize(fontSize, weight: UIFontWeightRegular)
                ]
            }

        self.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
    }
 }

C# / Xamarin:

segment.SetTitleTextAttributes(new UITextAttributes { 
    Font = UIFont.SystemFontOfSize(font_size) }, UIControlState.Normal);

以下是Swift版本的公认答案:

斯威夫特3:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
                                        for: .normal)

斯威夫特2.2:

let font = UIFont.systemFontOfSize(16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font], 
    forState: UIControlState.Normal)

我也遇到了同样的问题。这段代码为整个分段控件设置字体大小。类似的方法也可以用于设置字体类型。注意,这只适用于iOS5+

Obj C:

UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                       forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes 
                                forState:UIControlStateNormal];

编辑:UITextAttributeFont已弃用-使用NSFontAttributeName代替。

编辑#2:对于Swift 4 NSFontAttributeName已更改为NSAttributedStringKey.font。

斯威夫特5:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

斯威夫特4:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: font],
                                        for: .normal)

斯威夫特3:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
                                        for: .normal)

斯威夫特2.2:

let font = UIFont.systemFontOfSize(16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font], 
    forState: UIControlState.Normal)

多亏了@audrey-gordeev的Swift实现

另一种选择是对控件应用转换。然而,它将缩小一切,包括控制边界。

segmentedControl.transform = CGAffineTransformMakeScale(.6f, .6f);