【iOS】使用xib自定义UITableViewCell

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liudongdong19/article/details/89468427

你可以使用xib,推荐使用,创建cell,同时创建Xib即可,xib上面可以自定义布局

// 注册nib
tableView.registerNib(UINib(nibName: "nibName", bundle: mainBundle), forCellReuseIdentifier: "cellIdentifier");
// 注册类
tableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "cellIdentifier")

// 数据源
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier", forIndexPath: indexPath) as! TableViewCell
        return cell;
    }

使用注册类的时候需要手写代码 
重写init(style: UITableViewCellStyle, reuseIdentifier: String?)方法,并在里面进行UI设置

1.自定义列

新建一个xib文件 carTblCell,拖放一个UITableViewCell,再拖放一个图片和一个文本框到tableviewcell上

并给我们的xib一个标识

为了学习,我这里的xib和后台的class是分开建的。我们再建一个cocoa touch class文件名称为CarCellTableViewCell继承自UITableViewCell

并把我们的xib和新建的CarCellTableViewCell建立联接

//  课程信息列表cell

import UIKit

class CourseViewCell: UITableViewCell {

    @IBOutlet weak var txtccredit: UILabel!
    @IBOutlet weak var txtcnum: UILabel!
    @IBOutlet weak var txtcname: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    //  cell填充函数
    func loadData(name:String,num:String,credit:String){
        txtcname.text = name;
        txtcnum.text = num;
    
        txtccredit.text = credit;
    }

    
}

2.关联cell和tableview

1. 在main.storyboard上拖放一个uitableview,并在后台代码建立输出联接

1.在load事件里注册xib

2.在tableveiw的方法里得到当前的列,指定数据源。

//  管理员界面----课程信息界面controller

import Foundation
import UIKit
import CoreData

class  CourseTableViewController: UITableViewController {
    
    var tablelist=[String](repeating: "CourseName", count: 99)
    var dataSource:Array<Course> = []
    let model_course1 = model_course()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView!.register(UINib(nibName:"CourseViewCell", bundle:nil),
                                 forCellReuseIdentifier:"cell")
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    //  列表行数
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return CourseItem().count
    }
    
    //  填充行
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
            as! CourseViewCell
        
        let name0 = (CourseItem()[indexPath.row].value(forKey: "cname")as? String)!
        let num0 = (CourseItem()[indexPath.row].value(forKey: "cnum")as? String)!
        let credit0 = (CourseItem()[indexPath.row].value(forKey: "ccredit")as? String)!
        
        cell.loadData(name:name0 , num:num0, credit: credit0)
        
        tablelist[indexPath.row] = name0
        return cell
    }
    //   修改课程信息
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sb = UIStoryboard(name: "Main", bundle: nil)
        
        let vc = sb.instantiateViewController(withIdentifier: "update_course") as! Course_updateViewController
        vc.data = dataSource[indexPath.row]
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func refreshData() {
        dataSource = model_course1.selectItem()!
        
        self.tableView.reloadData()
    }
    override func viewWillAppear(_ animated: Bool) {
        refreshData()
    }
    //  获取课程信息函数
    private   func  CourseItem()->[NSManagedObject]{
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let managedObectContext = appDelegate.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Course")
        do {
            let fetchedResults = try managedObectContext.fetch(fetchRequest) as? [NSManagedObject]
                return fetchedResults!
            } catch  {
            fatalError("获取失败")
        }
    }
    //  删除课程信息函数
    private func delCourse(cname:String){
        let app = UIApplication.shared.delegate as! AppDelegate
        let contexts = app.persistentContainer.viewContext
        let entityName = "Course"
        let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
        let entity = NSEntityDescription.entity(forEntityName: entityName, in: contexts); fetchRequest.entity = entity
        let predicate = NSPredicate.init(format: "cname = '"+cname+"'", "")
        fetchRequest.predicate = predicate
        do {
            let fetchedObjects = try contexts.fetch(fetchRequest) as! [Course]
            for one: Course in fetchedObjects { contexts.delete(one)
                app.saveContext() } }
        catch {
            let nserror = error as NSError
            fatalError("查询错误: \(nserror), \(nserror.userInfo)")
        }
        
        
    }
    //  右滑菜单
    override func  tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.delete
        
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCellEditingStyle.delete {
        
            delCourse(cname:tablelist[indexPath.row])
            self.tableView!.reloadData()
            refreshData()
        }
    }
    
}

猜你喜欢

转载自blog.csdn.net/liudongdong19/article/details/89468427