读书笔记

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

2017-06-09  本文已影响0人  一梦换须臾_

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

通过Xcode中的storyboard

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

创建List

1.gif

自定义表格单元

将表格单元与Code关联

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

加载数据

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
    
  }
}
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]
}
override func viewDidLoad() {
    super.viewDidLoad()    
    // Load the sample data.
    loadSampleMeals()
}

将数据与表格关联

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
}
image.png

通过代码自定义

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

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()
 }
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

上一篇 下一篇

猜你喜欢

热点阅读