简体   繁体   English

如何从 iOS 设置中检测动态字体大小的变化?

[英]How to detect Dynamic Font size changes from iOS Settings?

Inside settings->general->text size, after changing the text size, I'd have to exit my own app to have the sizes applied to在 settings->general->text size 中,更改文本大小后,我必须退出我自己的应用程序才能将大小应用于

 [UIFont preferredFontForTextStyle:..]

Is there a delegate or notification to notify my app to re-apply the new sizes?是否有委托或通知通知我的应用程序重新应用新尺寸?

Update: I tried the following but interestingly, the font size will apply after I BG and launch the app TWICE.更新:我尝试了以下但有趣的是,字体大小将在我 BG 并启动应用程序两次后应用。

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fromBg:) name:UIApplicationDidBecomeActiveNotification object:nil];

}


 -(void) fromBg:(NSNotification *)noti{

    self.headline1.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
    self.subHeadline.font = [UIFont preferredFontForTextStyle:UIFontTextStyleSubheadline];
    self.body.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    self.footnote.font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
    self.caption1.font = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1];
    self.caption2.font = [UIFont preferredFontForTextStyle:UIFontTextStyleCaption2];
//    [self.view layoutIfNeeded];

}

You listen for the Size Change Notification on UIContentSizeCategory . 您在UIContentSizeCategory侦听大小更改通知。

Swift 3.0: NSNotification.Name.UIContentSizeCategoryDidChange Swift 3.0: NSNotification.Name.UIContentSizeCategoryDidChange

Swift 4.0 or later: UIContentSizeCategory.didChangeNotification Swift 4.0或更高版本: UIContentSizeCategory.didChangeNotification

With Swift 5 and iOS 12, you can choose one of the three following solutions in order to solve your problem. 使用Swift 5和iOS 12,您可以选择以下三种解决方案之一来解决您的问题。


#1. #1。 Using UIContentSizeCategoryAdjusting 's adjustsFontForContentSizeCategory property 使用UIContentSizeCategoryAdjustingadjustsFontForContentSizeCategory属性

UILabel , UITextField and UITextView conform to UIContentSizeCategoryAdjusting protocol and therefore have an instance property called adjustsFontForContentSizeCategory . UILabelUITextFieldUITextView符合UIContentSizeCategoryAdjusting协议,因此具有名为adjustsFontForContentSizeCategory的实例属性。 adjustsFontForContentSizeCategory has the following declaration: adjustsFontForContentSizeCategory具有以下声明:

A Boolean value indicating whether the object automatically updates its font when the device's content size category changes. 一个布尔值,指示当设备的内容大小类别更改时对象是否自动更新其字体。

var adjustsFontForContentSizeCategory: Bool { get set }

The UIViewController implementation below shows how to detect and react to dynamic font size changes in iOS settings with adjustsFontForContentSizeCategory : 下面的UIViewController实现演示了如何使用adjustsFontForContentSizeCategory检测iOS设置中的动态字体大小更改并做出反应:

import UIKit

class ViewController: UIViewController {

    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        label.numberOfLines = 0
        label.font = .preferredFont(forTextStyle: UIFont.TextStyle.body)
        label.adjustsFontForContentSizeCategory = true
        view.addSubview(label)

        // Auto layout
        label.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        let widthConstraint = label.widthAnchor.constraint(equalToConstant: 300)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint])
    }

}

#2. #2。 Using UIContentSizeCategory 's didChangeNotification type property 使用UIContentSizeCategorydidChangeNotification类型属性

UIContentSizeCategory has a type property called didChangeNotification . UIContentSizeCategory有一个名为didChangeNotification的type属性。 didChangeNotification has the following declaration: didChangeNotification具有以下声明:

Posted when the user changes the preferred content size setting. 用户更改首选内容大小设置时发布。

static let didChangeNotification: NSNotification.Name

This notification is sent when the value in the preferredContentSizeCategory property changes. preferredContentSizeCategory属性中的值更改时,将发送此通知。 The userInfo dictionary of the notification contains the newValueUserInfoKey key, which reflects the new setting. 通知的userInfo字典包含newValueUserInfoKey键,它反映了新设置。

The UIViewController implementation below shows how to detect and react to dynamic font size changes in iOS settings with didChangeNotification : 下面的UIViewController实现演示了如何使用didChangeNotification检测iOS设置中的动态字体大小更改并做出反应:

import UIKit

class ViewController: UIViewController {

    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        label.numberOfLines = 0
        label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        view.addSubview(label)

        // Register for `UIContentSizeCategory.didChangeNotification`
        NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)

        // Auto layout
        label.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        let widthConstraint = label.widthAnchor.constraint(equalToConstant: 300)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint])
    }

    @objc func preferredContentSizeChanged(_ notification: Notification) {
        label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        /* perform other operations if necessary */
    }

}

#3. #3。 Using UITraitCollection 's preferredContentSizeCategory property 使用UITraitCollectionpreferredContentSizeCategory属性

UITraitCollection has a property called preferredContentSizeCategory . UITraitCollection有一个名为preferredContentSizeCategory的属性。 preferredContentSizeCategory has the following declaration: preferredContentSizeCategory具有以下声明:

The font sizing option preferred by the user. 用户首选的字体大小调整选项。

var preferredContentSizeCategory: UIContentSizeCategory { get }

With Dynamic Type, users can ask that apps display text using fonts that are larger or smaller than the normal font size defined by the system. 使用动态类型,用户可以要求应用程序使用大于或小于系统定义的普通字体大小的字体显示文本。 For example, a user with a visual impairment might request a larger default font size to make it easier to read text. 例如,具有视觉障碍的用户可能会请求更大的默认字体大小,以便更容易阅读文本。 Use the value of this property to request a UIFont object that matches the user's requested size. 使用此属性的值来请求与用户请求的大小匹配的UIFont对象。

The UIViewController implementation below shows how to detect and react to dynamic font size changes in iOS settings with preferredContentSizeCategory : 下面的UIViewController实现显示了如何使用preferredContentSizeCategory检测iOS设置中的动态字体大小更改并做出反应:

import UIKit

class ViewController: UIViewController {

    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        label.numberOfLines = 0
        label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
        view.addSubview(label)

        // Auto layout
        label.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        let verticalConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        let widthConstraint = label.widthAnchor.constraint(equalToConstant: 300)
        NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint])
    }

    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)

        if previousTraitCollection?.preferredContentSizeCategory != traitCollection.preferredContentSizeCategory {
            self.label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body)
            /* perform other operations if necessary */
        }
    }

}

Sources: 资料来源:

Adding on to Imanou Petit 's Answer添加到Imanou Petit 的回答

You can also do this to get the size:您也可以这样做以获得尺寸:

let contentSize = traitCollection.preferredContentSizeCategory
if contentSize.isAccessibilityCategory {
   if contentSize >= .accessibilityLarge{
        print("larger than or equal to accessibility large")
    }else {
        print("lower than large")
    }
} else {

    print("not accessibility")
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM