在 Swift 中禁用动态类型

Disabling Dynamic Type in Swift

我有一个基于 Sprite Kit 的游戏,它在其中一个场景中使用 UIView,我这样做是为了利用 UITableViewController 来显示游戏设置屏幕。

我 运行 遇到的困难是,当用户将他们的 iPad 系统辅助功能设置为使用(超)大字体时,UITableView 中的文本对于单元格来说太大了,并且它看起来很傻。

我想做的是直接禁用应用程序中的动态类型,以便它始终在单元格中显示相同大小的类型。

我找到了另一个类似的帖子 (here),但回复提供了 Objective-C 回复:

#import <objc/runtime.h>

@implementation AppDelegate

NSString* swizzled_preferredContentSizeCategory(id self, SEL _cmd) {
    return UIContentSizeCategoryLarge;  // Set category you prefer, Large being iOS' default.
}

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    Method method = class_getInstanceMethod([UIApplication class], @selector(preferredContentSizeCategory));
    method_setImplementation(method, (IMP)swizzled_preferredContentSizeCategory);

    ...
}

我需要在 Swift 中执行此操作。

在 Swift 和 Xcode 7+ 中做同样事情的正确方法是什么?

好的,首先让我这么说:虽然我很高兴能够快速找到一种方法来容纳 iOS 辅助功能设置提供的动态文本(我将在秒)我认为得到原始问题的答案仍然很重要。

也就是说,这是我对 table 视图代码所做的,以尊重一些用户需要的更大的类型。这是一个两步过程。首先,添加:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

到 viewDidLoad 方法。然后,在 cellForRowAtIndexPath 方法中,在 return 单元格之前添加以下内容:

cell.textLabel!.numberOfLines = 0

祝你好运,如果你有原始问题,请添加一个答案:)

感谢 提供解决方案。 这是原问题的答案:

"preferredContentSizeCategory"在Objective-C中是方法,在Swift中是只读变量。

所以在你的 AppDelegate 中是这样的:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    // MARK: - UIApplicationDelegate

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

        UIApplication.classInit

        self.window = UIWindow(frame: UIScreen.main.bounds)
        ...
        self.window?.makeKeyAndVisible()
        return true
    }
}

// MARK: - Fix Dynamic Type

extension UIApplication {

    static let classInit: Void = {
        method_exchangeImplementations(
            class_getInstanceMethod(UIApplication.self, #selector(getter: fixedPreferredContentSizeCategory))!,
            class_getInstanceMethod(UIApplication.self, #selector(getter: preferredContentSizeCategory))!
        )
    }()

    @objc
    var fixedPreferredContentSizeCategory: UIContentSizeCategory {
        return .large
    }
}

What I would like to do is straight up disable the dynamic type within the app so it always displays the same sized type in the cells.

动态类型仅适用于已实现 text styles.

的文本

因此,如果您总是希望禁用动态类型并且在单元格中显示相同大小的类型,请不要使用文本样式也不包含 image size adjustment

但是,如果您确实想使用文本样式,请不要在 Interface Builder 中为每个文本元素勾选 Automatically Adjusts Font (相当于代码中的 adjustsFontForContentSizeCategory.