Swift项目 iOS10 UILabel显示不全 添加全局自适应
1. 新建一个Swift文件
代码:
//
// Commen.swift
// label文本添加自适应
//
// Created by xiaoniu on 16/9/20.
// Copyright © 2016年 xiaoniu. All rights reserved.
//
import Foundation
import UIKit
func swizzlingMethod(clzz: AnyClass, oldSelector: Selector, newSelector: Selector) {
let oldMethod = class_getInstanceMethod(clzz, oldSelector)
let newMethod = class_getInstanceMethod(clzz, newSelector)
method_exchangeImplementations(oldMethod, newMethod)
}
extension UIView {
func layoutSubviewsAndAdjust() {
self.layoutSubviewsAndAdjust()
if self.isKindOfClass(UILabel.classForCoder()) {
let label = self as! UILabel
label.adjustsFontSizeToFitWidth = true
label.backgroundColor = UIColor.yellowColor()
}
}
}
2. AppDelegate调用swizzlingMethod
代码:
//
// AppDelegate.swift
// label文本添加自适应
//
// Created by xiaoniu on 16/9/20.
// Copyright © 2016年 xiaoniu. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
swizzlingMethod(UILabel.self, oldSelector: "layoutSubviews", newSelector: "layoutSubviewsAndAdjust")
return true
}
}