UITableViewCell在Swift中

12

这是一个使用UITableViewControllerCoreData的示例代码。主文件为MainTableViewController.swift

import UIKit
import CoreData

class MainTableViewController: UITableViewController {

var results:AddrBook[]=[]

init(style: UITableViewStyle) {
    super.init(style: style)
}

init(coder aDecoder: NSCoder!) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func viewDidAppear(animated: Bool) {
    let request = NSFetchRequest(entityName: "Person")
    request.returnsObjectsAsFaults = false
    let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    let context:NSManagedObjectContext = appDelegate.managedObjectContext
    results  = context.executeFetchRequest(request, error: nil) as AddrBook[]
    self.tableView.reloadData()
}

override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
    return 1
}

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

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell! {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

    if !cell {
        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
    }

    cell!.textLabel.text = results[indexPath.row].lastname + " " + results[indexPath.row].firstname

    return cell
}

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject?) {

    var indexPath = self.tableView.indexPathForSelectedRow()
    let destViewController:DetailViewController! = segue.destinationViewController as DetailViewController

    if segue.identifier == "editPerson" {
        destViewController.receivedPerson = results
        destViewController.indexPath = indexPath
    }
}
}

如果在cellForRowAtIndexPath中使用以下代码:

cell!.textLabel.text = results[indexPath.row].lastname + " " + results[indexPath.row].firstname

那么一切都好。但如果我使用这个:

cell!.textLabel.text = results[indexPath.row].lastname
cell!.detailTextLabel.text = results[indexPath.row].firstname

我看到了错误:无法解包Optional.None

怎么回事?请帮忙。

这里是其他类的代码,以防万一

UIViewController类用于添加和编辑记录(DetailViewController.swift):

import UIKit
import CoreData

class DetailViewController: UIViewController {

@IBOutlet var currentOperation : UILabel = nil
@IBOutlet var firstnameField : UITextField = nil
@IBOutlet var lastnameField : UITextField = nil

var indexPath = NSIndexPath()
var receivedPerson:AddrBook[]=[]

init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}

init(coder aDecoder: NSCoder!) {
    super.init(coder: aDecoder)
}

override func viewDidLoad() {
    super.viewDidLoad()

    if !receivedPerson.isEmpty {        // If selected row in tableview in MainTableViewController
        currentOperation.text = "Edit Person"
        firstnameField.text = receivedPerson[indexPath.row].firstname
        lastnameField.text = receivedPerson[indexPath.row].lastname
    }
    else {       // If pressed "+" in MainTableViewController
        currentOperation.text = "Add Person"
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

@IBAction func saveButton(sender : AnyObject) {

    let appDelegate:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    let context:NSManagedObjectContext = appDelegate.managedObjectContext

    if receivedPerson.isEmpty {      // If pressed "+" in MainTableViewController
        let projectEntity = NSEntityDescription.entityForName("Person", inManagedObjectContext: context)
        var newPerson = AddrBook(entity: projectEntity, insertIntoManagedObjectContext: context)
        newPerson.lastname = lastnameField.text
        newPerson.firstname = firstnameField.text
    }
    else {       // If selected row in tableview in MainTableViewController
        receivedPerson[indexPath.row].firstname = firstnameField.text
        receivedPerson[indexPath.row].lastname = lastnameField.text
    }

    context.save(nil)
    self.navigationController.popViewControllerAnimated(true)
}

}

用于CoreData的AddrBook.swift类:

import UIKit
import CoreData

@objc(AddrBook)
class AddrBook: NSManagedObject {

    @NSManaged var lastname:String
    @NSManaged var firstname:String
}
3个回答

26

使用

cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")

相反地

cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

Swift 4+

使用

cell = UITableViewCell(style: .value1, reuseIdentifier: "Cell")

反而

cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")

13

对于 Swift 4+,请使用:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")

        if( !(cell != nil))
        {
            cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
        }

        cell!.textLabel?.text = "Hello"
        return cell!
    }

10
为什么看起来不自然的 if( !(cell != nil));难道 if cell == nil 不可以吗? - meaning-matters

0
尝试像这样使用。
只需避免感叹号。
cell.text = results[indexPath.row].lastname as NSString
cell.detailTextLabel.text = results[indexPath.row].firstname as NSString

我看到你的代码有很多错误!!


如果我删除感叹号,系统会在函数头中的选项和if !cell上发誓。我在函数头中采用了一组选项,以便系统不会生成错误。但是当您使用表达式cell.detailTextLabel.text = results[indexPath.row].firstname as NSString时,我看到相同的错误 - 无法解包Optional.None - Alexey Nakhimov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接