美文网首页读书笔记
浅谈UITableView在Swift中的应用与实现

浅谈UITableView在Swift中的应用与实现

作者: 一梦换须臾_ | 来源:发表于2017-06-09 15:00 被阅读0次

在移动端应用中,很多情况下我们需要频繁与表格、列表这类的UI组件打交道,由于移动端设备的屏幕较小,所以在iOS上组织多条信息,UITableView成为了相当得力的助手,下面我们就开始讨论一下UITableView在Swift中的实现

通过Xcode中的storyboard

Xcode中Swift开发者提供了很多便捷的工具,比如可以实现拖拽功能的storyboard,在storyboard中,每一个视图(view)都有一个对应的controller进行管理,因此我们接下来的大部分操作是基于storyboard的

创建List

  • 打开 utility area 中的 Object library. (或者, 选择 View > Utilities > Show Object Library.)

  • 在 Object library 中, 找到 Table View Controller 对象.

  • 从列表中拖拽出一个 Table View Controller 对象, 并且将其放置在左侧的scene中一个合适的位置上.

1.gif
  • 然后我们直接运行项目,可以查看到表格的视图已经出现
  • image.png

自定义表格单元

  • 我们先创建一个自定义表格的控制器类,步骤如下

    1. 新建一个类
    2. 选择iOS标签卡
    3. 选择Cocoa Touch Class
    4. 选择SubClass为 UITableViewCell
    5. 然后选择语言为Swift
  • 然后我们在storyboard中配置Table View中的Cell对应到我们刚才创建的类


    image.png
  • 然后我们仍然通过上述的 utility area 中的对象在Cell中拖拽出如下的界面

  • image.png

将表格单元与Code关联

  • image.png
  • 通过开发者视图转换的方式将XCode的界面调整成如上图所示

  • 将上述Cell中各元素与上面我们创建的TableViewCell类形成一一对应的关系

//UI中元素在TableViewCell类中的体现
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!

加载数据

  • 先创建我们的实体对象类,存放的数据内容对应到一个Cell
class Meal {
    
    //MARK: Properties
    
    var name: String
    var photo: UIImage?
    var rating: Int
    
    init?(name: String, photo: UIImage?, rating: Int) {
    
      // The name must not be empty
      guard !name.isEmpty else {
          return nil
      }
    
      // The rating must be between 0 and 5 inclusively
      guard (rating >= 0) && (rating <= 5) else {
          return nil
      }
    
      // Initialize stored properties.
      self.name = name
      self.photo = photo
      self.rating = rating
    
  }
}
  • 然后我们创建一个UITableViewControllerMealTableViewController,我们需要在这个类里面填写逻辑和处理数据,使数据与绑定的Table View对应

  • 我们先定义存储数据的对象 meals ,并定义初始化方法

var meals = [Meal]()
private func loadSampleMeals() {
    
    let photo1 = UIImage(named: "meal1")
    let photo2 = UIImage(named: "meal2")
    let photo3 = UIImage(named: "meal3")
    
    guard let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else {
        fatalError("Unable to instantiate meal1")
    }
    
    guard let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else {
        fatalError("Unable to instantiate meal2")
    }
    
    guard let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else {
        fatalError("Unable to instantiate meal2")
    }
    
    meals += [meal1, meal2, meal3]
}
  • 然后在TableViewController中重载父类方法 viewDidLoad() ,需要调用数据初始化方法
override func viewDidLoad() {
    super.viewDidLoad()    
    // Load the sample data.
    loadSampleMeals()
}

将数据与表格关联

  • 接下来我们需要将定义好的TableViewController与UI中所需要的DataSource关联起来
  • Table View展示元素所必需的几个关于DataSource方法如下
func numberOfSections(in tableView: UITableView) -> Int
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
  • 重载的方法实现如下
//该方法返回的值代表了Table View需要呈现几个sections
override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
//该方法返回值代表了在该Table View Controller控制下的Table View对应的DataSource有多少数据
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return meals.count
}
//该方法表示了对于每一行Cell,Cell内部的内容应该被如何渲染
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    // Table view cells are reused and should be dequeued using a cell identifier.
    let cellIdentifier = "MealTableViewCell"
    
    guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell  else {
        fatalError("The dequeued cell is not an instance of MealTableViewCell.")
    }
    
    // Fetches the appropriate meal for the data source layout.
    let meal = meals[indexPath.row]
    
    cell.nameLabel.text = meal.name
    cell.photoImageView.image = meal.photo
    cell.ratingControl.rating = meal.rating
    
    return cell
}
  • 将Controller与UI绑定
image.png
  • 重新启动项目,观察到Table中有了我们加入的几个Cell元素


    image.png

通过代码自定义

通过代码实现Table View的自定义本质上和上述借助storyboard的方法一样,实际操作上有一些不同

  • 创建一个UITableViewCell(并创建xib)命名为 DemoListCell


    image.png
  • 在DemoListCell.xib中画出你想要的cell样式(AutoLayout),另外注意要给Cell制定 IdentityId: DemoListID


    image.png
  • 然后类似的,将xib中的自定义元素与Cell的类进行元素绑定

  • 新建一个控制器类

class MainViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
// 定义好DataSource
let cellId = "DemoListID" //获取CellId
var tableData: (titles:[String], values:[String])? //定义一个数据源
// 在viewDidLoad()方法中创建了Table View
override func viewDidLoad() {
     super.viewDidLoad()
     self.title = "主页"
     self.view.backgroundColor = UIColor.whiteColor()

     //demoList的设置
     self.demoList.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
     //下面代码是用来去掉UITableView的Cell之间的线
     //self.demoList.separatorStyle = UITableViewCellSeparatorStyle.None
     let nib = UINib(nibName: "DemoListCell", bundle: nil) //nibName指的是我们创建的Cell文件名
     self.demoList.registerNib(nib, forCellReuseIdentifier: cellId)
     self.demoList.delegate = self
     self.demoList.dataSource = self
     self.view.addSubview(self.demoList)
     self.showData()
 }
  • 然后重载了相关DataSource的上述的几个方法
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
     return 1
 }

 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

     guard let count:Int = self.tableData!.titles.count else {
         print("没有数据")
     }

     return count
 }
 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCellWithIdentifier(self.cellId, forIndexPath: indexPath) as! DemoListCell
     //cell.cellImg.image = UIImage(named: powerData[indexPath.row][2])
     cell.cellLabel.text = self.tableData!.titles[indexPath.row]

     return cell
 }

 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
 {
     let index = indexPath.row
     let storyID = tableData!.values[index] as String
     let storyboard = UIStoryboard(name: "Main", bundle: nil)
     var nextView:UIViewController
     switch storyID {
     case "SCLAlert":
         nextView = storyboard.instantiateViewControllerWithIdentifier(storyID) as! SCLAlertDemoViewController
     case "SwiftNotice":
         nextView = storyboard.instantiateViewControllerWithIdentifier(storyID) as! SwiftNoticeDemoViewController
     case "CNPPopup":
         nextView = storyboard.instantiateViewControllerWithIdentifier(storyID) as! CNPPopupDemoViewController
     case "ClosureBack":
         nextView = LWRootViewController()
     default:
         nextView = storyboard.instantiateViewControllerWithIdentifier("SCLAlert") as! SCLAlertDemoViewController
     }
     self.navigationController?.pushViewController(nextView, animated: true)
 }

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
 {
     return 50
 }

参考资料

Swift编程(一):UITableView及自定义Cell的Xib
Start Developing iOS (Swift) : Create a Table View

相关文章

网友评论

    本文标题:浅谈UITableView在Swift中的应用与实现

    本文链接:https://www.haomeiwen.com/subject/elvxqxtx.html