Как сменить шрифт и имя шрифта uisegmentedcontrol программно на быстрый?
Как изменить размер шрифта и имя шрифта uisegmentedcontrol программно? Я быстро использовал.
Вот мой код:
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
Пользовательский интерфейс может использовать внешний вид управления, лучшее место для добавления его в делегат приложения, метод 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)
Ответ 2
Этот ответ датирован, но для тех, кто ищет быстрое решение, вы можете попробовать этот подход:
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)
}
Обязательно добавьте stylizeFonts() в свой viewDidLoad или как отдельную функцию, если вы являетесь подклассом.
Ответ 3
Для Swift 4
let font: [AnyHashable : Any] = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 17)]
segmentedControl.setTitleTextAttributes(font, for: .normal)
Ответ 4
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)
Ответ 5
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:
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)
}
Ответ 7
В целях расширения 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)
Ответ 8
Использование @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)
Ответ 9
Swift 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)
}
}
Ответ 10
Для Swift 4
let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font],
for: .normal)
Ответ 11
Для быстрого 3
UISegmentedControl.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.white], for: .selected)