2017-07-07 42 views
-1

我遇到了問題。有了這裏的所有幫助,我無法自己解決,所以我想再次獲得一些幫助。CoreData和在Swift3中添加文本框

所以我只是直接問,但我試圖通過編程來創建一個屬性,因爲在我的應用程序中,我以編程方式創建了文本框,用戶可以根據自己的需要創建文本框。所以我想存儲這些新建的文本框文本並以不同的視圖顯示它們。我如何用CoreData來做到這一點?我想我會創建一個新的屬性並將它們存儲在那裏,並使用這些屬性來計算並在第二個視圖中創建文本框,但我不知道如何實現。

+0

通常,您不能*通過編程方式編寫屬性*。核心數據模型在運行時不可修改。 – vadian

回答

0

我想你可以爲textfield創建一個實體,並在創建新文本字段時創建此實體的商店實例。並且您可以輕鬆處理這些實體數組以處理文本字段。

+0

非常感謝您的幫助。它幫助我很多。但是我非常抱歉問,但是我每次創建新的textField時如何創建&存儲實例?我已經使用了一段時間的核心數據,但不是這種方式,我只是不知道如何:( – dropscar

+0

剛剛到核心數據文檔,你可以得到所有信息 https://developer.apple.com/library /content/documentation/Cocoa/Conceptual/CoreData/index.html –

0
import UIKit 
import CoreData 

class ViewController: UIViewController , UITextFieldDelegate 
{ 

    var txtName:UITextField! 
    var btnfirst :UIButton! 
    let appDelegate = UIApplication.shared.delegate as! AppDelegate 
    var managedContext:NSManagedObjectContext! 
    var entity:NSEntityDescription! 
    var stname: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) 



    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 

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") 


         do { 
          try managedContext.save() 

         } catch let error as Error! { 
          print(error.localizedDescription) 
         } 

} 
}