如何在 Swift 中以编程方式更改 UISegmentedControl 的字体大小和字体名称?

46
如何以编程方式更改uisegmentedcontrol的字体大小和字体名称?我使用了Swift。
这是我的代码:
self.mysegmentedControl = UISegmentedControl(items: [
        NSLocalizedString("Aaaaaa", comment: ""),
        NSLocalizedString("Bbbbbb", comment: ""),
        NSLocalizedString("Cccccc", comment: ""),
        NSLocalizedString("Dddddd", comment: ""),
        NSLocalizedString("Eeeeee", comment: ""),
        ])
self.mysegmentedControl.addTarget(self, action: "mysegmentedControlDidChange:", forControlEvents: .ValueChanged)
self.mysegmentedControl.selectedSegmentIndex = 0

致敬。

16个回答

84

UI 可以控制外观,最好的方法是在 app delegate 的 didFinishLaunchingWithOptions 方法中添加设置。如果您想一次性将同样的属性设置到项目中的每个 UISegmentedControl 上,则可以使用此方法:

let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
UISegmentedControl.appearance().setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)

但是如果你要为一个UISegmentedControl设置属性,或者如果你想根据某些条件更频繁地更改它,请使用这个UISegmentedControl方法:

func setTitleTextAttributes(_ attributes: [NSObject : AnyObject]?,
                   forState state: UIControlState)

例子:

let attr = NSDictionary(object: UIFont(name: "HelveticaNeue-Bold", size: 16.0)!, forKey: NSFontAttributeName)
seg.setTitleTextAttributes(attr as [NSObject : AnyObject] , forState: .Normal)

我能否在应用程序委托中以编程方式编辑UISegmentedControl的大小(我的意思是宽度和高度)?如果可以,如何实现? - user1858725
我建议使用自动布局,并为每个分段控件添加一个NSLayoutConstraint。 - dulgan
+1 建议使用 UIAppearance 代理,-1 建议插入到应用程序委托中。时间很重要,必须在加载任何其他视图之前完成,因此应在“-applicationDidFinishLaunching:”完成之前完成,但更好的架构是将所有演示逻辑移动到不同的类中,其唯一责任是演示和样式。 - Tim

29

针对Swift 4

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

你在哪里写字体名称? - PlateReverb
`我用了这个代替(Swift 5)let fontAttributes: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)] segmentedControl.setTitleTextAttributes(fontAttributes, for: .normal) - undefined

21

这个回答有点过时,但是对于那些正在寻找Swift解决方案的人们,你可能想尝试这种方法:

这个回答过时了,但对于那些正在寻找Swift解决方案的人,可以尝试以下方法:

func stylizeFonts(){
    let normalFont = UIFont(name: "Helvetica", size: 16.0)
    let boldFont = UIFont(name: "Helvetica-Bold", size: 16.0)

    let normalTextAttributes: [NSObject : AnyObject] = [
        NSForegroundColorAttributeName: UIColor.blackColor(),
        NSFontAttributeName: normalFont!
    ]

    let boldTextAttributes: [NSObject : AnyObject] = [
        NSForegroundColorAttributeName : UIColor.whiteColor(),
        NSFontAttributeName : boldFont!,
    ]

    self.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
    self.setTitleTextAttributes(normalTextAttributes, forState: .Highlighted)
    self.setTitleTextAttributes(boldTextAttributes, forState: .Selected)
}

如果您正在进行子类化,请确保在viewDidLoad中添加stylizeFonts()或作为单独的函数。


你的代码中,在 boldFont 后面有一个多余的逗号,请注意。 - Ben

11

Greg的答案已更新为Swift3:

let attr = NSDictionary(object: UIFont(name: "OpenSans", size: 12.0)!, forKey: NSFontAttributeName as NSCopying)
UISegmentedControl.appearance().setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)

8

@Jordan Montel的答案已更新,适用于Swift 5。更改字体和字号的工作代码。

extension UISegmentedControl {
    func font(name:String?, size:CGFloat?) {
        let attributedSegmentFont = NSDictionary(object: UIFont(name: name!, size: size!)!, forKey: NSAttributedString.Key.font as NSCopying)
        setTitleTextAttributes(attributedSegmentFont as [NSObject : AnyObject] as [NSObject : AnyObject] as? [NSAttributedString.Key : Any], for: .normal)
    }
}

"segControl"是您的IBOutlet名称:

segControl.font(name: "Your Font Name", size: 10)

7

Swift 2.0

    override func viewDidLayoutSubviews() {
        let attributedSegmentFont = NSDictionary(object: UIFont(name: "Roboto-Regular", size: 14.0)!, forKey: NSFontAttributeName)

    dashBoardSegment.setTitleTextAttributes(attributedSegmentFont as [NSObject : AnyObject], forState: .Normal)
    }

如果需要更改所有分段控件,请使用以下方法:

UISegmentedControl.appearance().setTitleTextAttributes(attributedSegmentFont as [NSObject : AnyObject], forState: .Normal)

使用Swift扩展:

extension UISegmentedControl{
    func changeTitleFont(newFontName:String?, newFontSize:CGFloat?){
        let attributedSegmentFont = NSDictionary(object: UIFont(name: newFontName!, size: newFontSize!)!, forKey: NSFontAttributeName)
        setTitleTextAttributes(attributedSegmentFont as [NSObject : AnyObject], forState: .Normal)
    }
}

实现扩展:

override func viewDidLayoutSubviews() {
    dashBoardSegment.changeTitleFont("Roboto-Regular", newFontSize: 14.0)
}

6

Swift3

override func viewDidLayoutSubviews() {
    let attr = NSDictionary(object: UIFont(name: "Chalkduster", size: 14.0)!, forKey: NSFontAttributeName as NSCopying)
    segmentedControl.setTitleTextAttributes(attr as [NSObject : AnyObject] , for: .normal)
}

5

回答jeff-ziligy后,我对代码进行了测试,并找到了Swift 5.1的更新代码:

extension UISegmentedControl {

func setFontSize(fontSize: CGFloat) {

    let normalTextAttributes: [NSObject : AnyObject] = [
        NSAttributedString.Key.foregroundColor as NSObject: UIColor.black,
        NSAttributedString.Key.font as NSObject : UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.medium)
    ]

    let boldTextAttributes: [NSObject : AnyObject] = [
        NSAttributedString.Key.foregroundColor as NSObject : UIColor.black,
        NSAttributedString.Key.font as NSObject : UIFont.systemFont(ofSize: fontSize, weight: UIFont.Weight.medium),
    ]

    self.setTitleTextAttributes(normalTextAttributes as? [NSAttributedString.Key : Any], for: .normal)
    self.setTitleTextAttributes(normalTextAttributes as? [NSAttributedString.Key : Any], for: .highlighted)
    self.setTitleTextAttributes(boldTextAttributes as? [NSAttributedString.Key : Any], for: .selected)
  }
}

在ViewDidLoad()中实现的部分是相同的:
yourSegmentedControl.setFontSize(20)

感谢您添加了在viewDidLoad中放置部分的说明。 - bpedit

4

通过扩展mvien的优秀Swift方法,我创建了一个SegmentedControl扩展:

extension UISegmentedControl {

    func setFontSize(fontSize: CGFloat) {

        let normalTextAttributes: [NSObject : AnyObject] = [
            NSForegroundColorAttributeName: UIColor.blackColor(),
            NSFontAttributeName: UIFont.systemFontOfSize(fontSize, weight: UIFontWeightRegular)
        ]

        let boldTextAttributes: [NSObject : AnyObject] = [
            NSForegroundColorAttributeName : UIColor.whiteColor(),
            NSFontAttributeName : UIFont.systemFontOfSize(fontSize, weight: UIFontWeightMedium),
        ]

        self.setTitleTextAttributes(normalTextAttributes, forState: .Normal)
        self.setTitleTextAttributes(normalTextAttributes, forState: .Highlighted)
        self.setTitleTextAttributes(boldTextAttributes, forState: .Selected)
    }
}

只需将上述扩展代码添加到您的项目中,然后按如下方式使用:

yourSegmentedControl.setFontSize(20)

3

对于Swift 4

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接