Swift UITableView 插入及自動滾動到底部
阿新 • • 發佈:2019-02-03
// // ViewController.swift // Proclamation // // Created by on 16/12/15. // Copyright © 2016年 . All rights reserved. // import UIKit class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { var tableView = UITableView() var rightButtonItem:UIBarButtonItem? var items = ["1","2","3","4","5","6","7","8","9"] override func viewDidLoad() { super.viewDidLoad() initView() setupRightBarButtonItem() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initView(){ // 初始化tableView的資料 self.tableView=UITableView(frame:self.view.frame,style:UITableViewStyle.Plain) // 設定tableView的資料來源 self.tableView.dataSource=self // 設定tableView的委託 self.tableView.delegate = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(self.tableView) } //加右邊按鈕 func setupRightBarButtonItem() { self.rightButtonItem = UIBarButtonItem(title: "Add", style: UIBarButtonItemStyle.Plain, target: self,action: #selector(ViewController.rightBarButtonItemClicked)) self.navigationItem.rightBarButtonItem = self.rightButtonItem } //增加事件 func rightBarButtonItemClicked() { let row = self.items.count let indexPath = NSIndexPath(forRow:row,inSection: 0) self.items.append("\(row + 1)") self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .None) // scroll to bottom self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: self.items.count - 1,inSection: 0), atScrollPosition: .Bottom, animated: true) } //總行數 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return self.items.count } //載入資料 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell let row=indexPath.row as Int cell.textLabel!.text=self.items[row] cell.imageView!.image = UIImage(named:"speaker") return cell; } //刪除一行 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath){ let index=indexPath.row as Int self.items.removeAtIndex(index) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top) NSLog("刪除\(indexPath.row)") } //選擇一行 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){ let alert = UIAlertView() alert.title = "提示" alert.message = "你選擇的是\(self.items[indexPath.row])" alert.addButtonWithTitle("Ok") alert.show() } }