如何在swift上以编程方式更改uisegmentedcontrol的字体大小和字体名称?

Posted

技术标签:

【中文标题】如何在swift上以编程方式更改uisegmentedcontrol的字体大小和字体名称?【英文标题】:how to change font size and font name of uisegmentedcontrol programmatically on swift? 【发布时间】:2015-03-12 11:10:22 【问题描述】:

如何以编程方式更改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

问候。

【问题讨论】:

【参考方案1】:

Objective-C 版本:

NSDictionary *attributes = @ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Light" size:17] ;
[segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];

【讨论】:

【参考方案2】:

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

【讨论】:

【参考方案3】:

对于 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()中up实现的部分是一样的:

yourSegmentedControl.setFontSize(20)

【讨论】:

感谢您添加关于放置在 viewDidLoad 中的部分。【参考方案4】:

Xamarin/C# 解决方案

以下是根据批准的答案使用 UIAppearance 进行更改的细分:

var font = UIFont.FromName("HelveticaNeue-Bold", 16f);
var textAttributes = new UITextAttributes  Font = font ;
UISegmentedControl.Appearance.SetTitleTextAttributes(textAttributes, 
    UIControlState.Normal);

【讨论】:

【参考方案5】:

对于 Swift 4

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

【讨论】:

【参考方案6】:

斯威夫特 4

@IBOutlet var sgmentTypeSelect: UISegmentedControl!
        didSet 

            let normalTextAttributes: [NSAttributedStringKey : AnyObject] = [
                NSAttributedStringKey.foregroundColor : UIColor.themeGold,
                NSAttributedStringKey.font : UIFont.defaultMontserratFont(style: "SemiBold", size: 13)
            ]

            let selectedTextAttributes: [NSAttributedStringKey : AnyObject] = [
                NSAttributedStringKey.foregroundColor : UIColor.black,
                NSAttributedStringKey.font : UIFont.defaultMontserratFont(style: "Bold", size: 13)
            ]

            sgmentTypeSelect.setTitleTextAttributes(normalTextAttributes, for: .normal)
            sgmentTypeSelect.setTitleTextAttributes(normalTextAttributes, for: .highlighted)
            sgmentTypeSelect.setTitleTextAttributes(selectedTextAttributes, for: .selected)

        
    

【讨论】:

【参考方案7】:

使用@Alvin George 回答,因为我认为添加扩展来操作它是一个好主意(并为 Swift 4 改进它):

创建 UISegmentedControl 的扩展类,如UISegmentedControl+Additions.swift

import Foundation
import UIKit

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

在你的代码中使用它:

segmentedControl?.font(name: "My Font Name", size: 12)

【讨论】:

【参考方案8】:

对于 Swift 4

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

【讨论】:

字体名称写在哪里?【参考方案9】:

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)

【讨论】:

【参考方案10】:

对于 Swift 3

UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.white], for: .selected)

【讨论】:

【参考方案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)

【讨论】:

【参考方案12】:

UI 可以使用控件外观,添加它的最佳位置是在应用程序委托中,didFinishLaunchingWithOptions 方法,如果您想为项目中的每个 UISegmentedControls 设置一次相同的属性,请使用此:

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 大小(我的意思是宽度和高度)吗?如果可以,怎么做? 我建议使用自动布局并为每个 SegmentedControl 添加一个 NSLayoutConstraint +1 用于建议 UIAppearance 代理,-1 用于建议插入到应用程序委托中。时机很重要,在加载任何其他视图之前执行此操作,因此应该在完成 -applicationDidFinishLaunching: 之前完成,但是将所有表示逻辑移动到一个单独负责表示和样式的不同类是更好的架构。 【参考方案13】:

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)

【讨论】:

【参考方案14】:

通过扩展 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)

【讨论】:

【参考方案15】:

这个答案已经过时了,但是对于那些正在寻找快速解决方案的人,您可能想尝试这种方法:

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() 或作为单独的函数(如果您是子类化)。

【讨论】:

FYI,你有一个额外的逗号,让 boldTextAttributes 在 boldFont 之后!

以上是关于如何在swift上以编程方式更改uisegmentedcontrol的字体大小和字体名称?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iPhone 上以编程方式在 Swift 中将 UIViewController 呈现为弹出框

如何在 Android TV 上以编程方式更改电视频道

我们可以删除在 swift 上以编程方式添加的标签吗?

如何在 Android SDK 26 或更高版本上以编程方式重置锁屏密码

如何选择一个应用程序以在 Marshmallow 上以编程方式允许模拟位置?

在 Apple Watch 上以编程方式通知。 (WatchOS 3)