Created
May 24, 2020 06:04
-
-
Save MrFuFuFu/8e3778d8fb5a39e9b74211619caab4d6 to your computer and use it in GitHub Desktop.
NSKeyedUnarchiver.unarchivedObject has Font issues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var editText: UITextView! | |
@IBOutlet weak var showText: UITextView! | |
var attText: NSMutableAttributedString { | |
get { | |
let a = NSAttributedString(string: "这是非粗体\n", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]) | |
let b = NSAttributedString(string: "这是粗体\n", attributes: [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]) | |
let c = NSAttributedString(string: "这是非粗体\n", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white]) | |
let att = NSMutableAttributedString() | |
att.append(a) | |
att.append(b) | |
att.append(c) | |
return att | |
} | |
} | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
editText.allowsEditingTextAttributes = true | |
if let data = UserDefaults.standard.data(forKey: "AAA") { | |
let att = NSAttributedString.fromData(data) | |
editText.attributedText = att | |
showText.attributedText = att | |
} else { | |
editText.attributedText = attText | |
} | |
} | |
@IBAction func onResetClick(_ sender: UIButton) { | |
editText.attributedText = attText | |
} | |
@IBAction func onSaveClick(_ sender: UIButton) { | |
UserDefaults.standard.set(editText.attributedText.toData(), forKey: "AAA") | |
if let data = UserDefaults.standard.data(forKey: "AAA") { | |
showText.attributedText = NSAttributedString.fromData(data) | |
} | |
} | |
@IBAction func onToDismissKeyboard(_ sender: UITapGestureRecognizer) { | |
editText.resignFirstResponder() | |
showText.resignFirstResponder() | |
} | |
} | |
extension NSAttributedString { | |
func toData() -> Data { | |
return try! NSKeyedArchiver.archivedData(withRootObject: self, requiringSecureCoding: true) | |
} | |
static func fromData(_ data: Data) -> NSAttributedString? { | |
//This line of code report this issue: | |
//Client requested name ".PingFangSC-Medium", it will get TimesNewRomanPSMT rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[UIFont systemFontOfSize:] | |
if let attribute = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSAttributedString.self, from: data) { | |
return attribute | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment