我正在關注一個在線教程以構建雜誌類型的iOS應用程序。我試圖使用NSAttributedStringKey,但不斷收到如下所示的錯誤。有任何想法嗎?NSAttributedStringKey給出未解決的標識符錯誤
這是代碼導致錯誤行:
let attrs = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font] as [NSAttributedStringKey : Any]
我正在關注一個在線教程以構建雜誌類型的iOS應用程序。我試圖使用NSAttributedStringKey,但不斷收到如下所示的錯誤。有任何想法嗎?NSAttributedStringKey給出未解決的標識符錯誤
這是代碼導致錯誤行:
let attrs = [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: font] as [NSAttributedStringKey : Any]
您要使用的代碼在iOS的11增加了新的API,由於您使用的Xcode 8你不使用的iOS 11.所以你需要使用當前的(非beta版)API。
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
您試圖在iOS 11之前的版本(可能是iOS 10)上使用iOS 11 API。驚訝的是,你發現一個教程已經在使用測試版功能!
在此期間,試試這個。
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
,並應工作。
本示例僅適用於iOS11。
import UIKit
class VC: UIViewController {
@IBOutlet weak var usernameTxt: UITextField!
@IBOutlet weak var emailTxt: UITextField!
@IBOutlet weak var passTxt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
usernameTxt.attributedPlaceholder = NSAttributedString(string: "username", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder])
emailTxt.attributedPlaceholder = NSAttributedString(string: "email", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder])
passTxt.attributedPlaceholder = NSAttributedString(string: "password", attributes: [NSAttributedStringKey.foregroundColor: smackPurplePlaceholder])
}
}
該項目可能在不同版本的Swift中。
在Swift 4中,NSFontAttributeName已被替換爲NSAttributedStringKey.font。
這裏說NSFontAttributeName vs NSAttributedStringKey.font
需要確認將它的版本工作不到ios11
這是一個iOS的11 API。 – rmaddy
你看到什麼錯誤?另外,你使用的是什麼版本的Swift/Xcode? – chrismanderson
@chrismanderson錯誤是「使用未聲明的類型NSAttributedStringKey」Xcode版本 - 8.3.3。我認爲這與版本問題有關,但不知道是否有解決方法等。 – Johnm95