-1
我正在使用Swift。 我有一個快速的問題,並希望你能幫助。 我的問題是我如何從一個程序化的標籤和文本字段存儲數據,並在不同的視圖中再次顯示它? 任何提示將幫助我。非常感謝你。CoreData和標籤和文本框
我正在使用Swift。 我有一個快速的問題,並希望你能幫助。 我的問題是我如何從一個程序化的標籤和文本字段存儲數據,並在不同的視圖中再次顯示它? 任何提示將幫助我。非常感謝你。CoreData和標籤和文本框
我建議你創建一個自定義標籤和文本框(子類,從的UILabel,同時也是UITextField繼承),然後只存儲文本,色彩,佔位符,...
import UIKit
import CoreData
class ViewController: UIViewController , UITextFieldDelegate
{
var txtName:UITextField!
var txtEmail:UITextField!
var txtPassword:UITextField!
var btnfirst :UIButton!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var managedContext:NSManagedObjectContext!
var entity:NSEntityDescription!
var stname:String!
var stpass:String!
var stenno:String!
override func viewDidLoad()
{
super.viewDidLoad()
txtName = UITextField()
txtName.frame = CGRect(x: 10, y: 30, width: 300, height: 30)
txtName.borderStyle = UITextBorderStyle.roundedRect
txtName.backgroundColor = .yellow
txtName.placeholder = "Enter Your Name"
txtName.autocorrectionType = .no
txtName.clearButtonMode = .always
self.view.addSubview(txtName)
txtEmail = UITextField()
txtEmail.frame = CGRect(x: 10, y: 70, width: 300, height: 30)
txtEmail.backgroundColor = .yellow
txtEmail.placeholder = "Enter Your Email Address"
txtEmail.keyboardType = .emailAddress
txtEmail.autocorrectionType = .no
txtEmail.clearButtonMode = .always
txtEmail.borderStyle = UITextBorderStyle.roundedRect
view.addSubview(txtEmail)
txtPassword = UITextField()
txtPassword.placeholder = "Enter Password Your Choice"
txtPassword.frame = CGRect(x: 10, y: 110, width: 300, height: 30)
txtPassword.borderStyle = UITextBorderStyle.roundedRect
txtPassword.backgroundColor = .yellow
txtPassword.clearButtonMode = .always
txtPassword.autocorrectionType = .no
txtPassword.isSecureTextEntry = true
view.addSubview(txtPassword)
btnfirst = UIButton(type: .system)
btnfirst.setTitle("Press", for: .normal)
btnfirst.setTitleColor(.red, for: .normal)
btnfirst.frame = CGRect(x: 100, y: 200, width: 100, height: 30)
btnfirst.addTarget(self, action: #selector(benpress(sender:)),for: .touchUpInside)
btnfirst.backgroundColor = .green
self.view.addSubview(btnfirst)
}
func benpress(sender :UIButton)
{
stname = txtName.text
stenno = txtEmail.text
stemail = txtPassword.text
self.managedContext = self.appDelegate.persistentContainer.viewContext
entity = NSEntityDescription.entity(forEntityName: "Student", in: managedContext)
let storeStudent = NSManagedObject.init(entity: entity, insertInto: managedContext)
storeStudent.setValue(stname, forKey: "name")
storeStudent.setValue(stpass, forKey: "password")
storeStudent.setValue(stemail, forKey: "email")
do {
try managedContext.save()
} catch let error as Error! {
print(error.localizedDescription)
}
}
}
非常感謝你。我試過了,它給了我一個「let storeStudent = NSManagedObject.init(實體:entity,insertInto:managedContext)」錯誤,「錯誤是」致命錯誤:意外地發現零,同時展開一個可選值。你有什麼想法,爲什麼? – dropscar
我很抱歉,但這不起作用:(或者我改變了它有點我的自我,似乎運行,但每次我重新打開應用程序的數據已經消失,所以這個代碼沒有正確存儲。你可以給我嗎?非常感謝你的幫助 – dropscar