UI TableView单元格使用swift

时间:2015-09-07 08:09:32

标签: iphone swift uitableview core-data uiviewcontroller

作为iOS和Swift的初学者,我有一个项目必须有一个包含多个单元格的tableview,其中每个单元格都包含多种数据类型。即字符串,日期等,其中在一个视图控制器中,有用于查看单元格的表视图,第二个视图控制器用于创建单元格并输入数据,第三个视图用于在单击时显示相同的数据细胞。我决定使用coredata存储所有这些,因为我被告知它对于初学者来说效率最高,最简单。我在这个问题上使用了几个教程,但没有一个能解决我遇到的这类问题。最好的例子是联系人列表在iOS上的工作方式。 我到目前为止所做的代码是:

 var titleCellList = [NSManagedObject]()
 var infoCellList = [NSManagedObject]()

class CellsViewController: UIViewController, UITableViewDataSource,    UITableViewDelegate {

@IBOutlet var cellsTableView: UITableView!

//MARK: Default Functions

override func viewDidLoad() {
    super.viewDidLoad()
    title = "\"Lists\""
    cellsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    // Do any additional setup after loading the view.
}

// MARK:UITableViewDataSource

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return TitleCellList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
        let cellTitle = titleCellList[indexPath.row]
        cell.textLabel!.text = cellTitle.valueForKey("title") as? String

        return cell
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
    cellsTableView.reloadData()
}

// MARK:存储CoreData

 func saveName(name: String) {
    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let entity =  NSEntityDescription.entityForName("Data", inManagedObjectContext: managedContext)
    let title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)

    //3
    title.setValue(name, forKey: "title")

    //4
    var error: NSError?
    if !managedContext.save(&error) {
        println("Could not save \(error), \(error?.userInfo)")
    }
    //5
    titleCellList.append(title)
}

// MARK:获取CoreData

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    //1
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    //2
    let fetchRequest = NSFetchRequest(entityName:"Data")

    //3
    var error: NSError?
    let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

    if let results = fetchedResults {
        titleCellList = results
    } else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}

// MARK:表格编辑方法

func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}


func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if editingStyle == UITableViewCellEditingStyle.Delete {

            let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let context:NSManagedObjectContext = appDel.managedObjectContext!
            context.deleteObject(titleCellList[indexPath.row] as NSManagedObject)
            titleCellList.removeAtIndex(indexPath.row)
            context.save(nil)

            cellsTableView.reloadData()
        }
    }

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = indexPath.row
        println("Row: \(row)")

        println(titleCellList[row])
        performSegueWithIdentifier("checkCellSegue", sender: self)
    }

第二个视图控制器(用于创建包含数据的单元格)

class AddNewViewController: UIViewController, UITextFieldDelegate {


@IBOutlet var titleTextField: UITextField!
@IBOutlet var shortInfoTextView: UITextView!

//MARK: Default Functions

override func viewDidLoad() {
    super.viewDidLoad()
    self.titleTextField.delegate = self


    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

@IBAction func addDataButtonPressed(sender: UIButton) {

    if titleTextField.text != ""  {
    CellsViewController().saveName(titleTextField.text)
    titleTextField.text = ""
    shortInfoTextView.text = ""
        println("New title Added!")
    }else {
        println("No empty titles allowed!")
    }
}

现在,大部分代码来自教程,当我尝试添加其他数据实体时,它没有用。在数据模型中,我目前只有一个实体名为&#34; Data&#34;其中包含4个型号。因此,总而言之,我需要在一个实体中存储4个数据模型,并在单击一个单元格时将它们加载到不同的视图控制器上,当然,该单元格具有用户编写的标题。值得注意的是,我花了几个小时在网上搜索答案,所以这是我的最后一句话。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

所以,这是我在这个小问题上使用的一种方法。我基本上只是用prepareForSegue方法传递参数,在其中我只是传递我想在其他类/ VC中使用的数据。

守则:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    // Setter for Second VC, destination path --> var declarations in Second VC

    if segue.identifier == "checkCellSegue" {
        let destination = segue.destinationViewController as! SecondViewController
        if let indexPath = self.tableView?.indexPathForCell(sender as! UITableViewCell) {
            let object = fetchedResultsController?.objectAtIndexPath(indexPath) as? Data
            destination.cellTitle = object?.cellTitle
            destination.textViewInfo = object?.textViewInfo
            destination.timerValue = object?.timerValue

        }
    }  

所以,首先我们声明目标,它是我们的第二个VC的名称或你命名的任何名称。然后,由于我通过TableView单元访问数据,我们需要使用indexPath获取我的CoreData实体。之后,最终声明是Model Class,它包含来自实体的所有数据值,它将像单例一样工作。

destination.cellTitle // --> in the 2.nd VC we declared a new var called cellTitle, var cellTitle:String

object?.cellTitle  // --> in the model class "Data.swift" the declaration is @NSManaged var cellTitle:String

所以,就是这样。我在iOS上仍然是一个新手,所以如果有任何错误,请说出来。

相关问题