最近打算开始学习Swift,记录一下自己的学习路程吧 ~
UITableView基本算是最基础的,同时也是我们经常使用到的一个类了
感觉跟OC相比最大的改变就是用点语法代替了原来的[],界面方面个人感觉有点凌乱,找不到方法怎么办o(╯□╰)o
import UIKit
//添加代理
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//创建TableView
var tableView = UITableView()
var dataArr = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
dataArr = ["1","2","3","4","5","6","7","8","9","10"]
//初始化TableView
tableView = UITableView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height), style: UITableViewStyle.Plain)
tableView.dataSource = self
tableView.delegate = self
self.view.addSubview(tableView)
}
//Section
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}
//行数
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArr.count;
}
//cell高度
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80;
}
//cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellID = "cell";
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellID)
cell.textLabel?.text = String(dataArr[indexPath.row] as! String)
cell.detailTextLabel?.text = "test\(dataArr[indexPath.row])"
return cell
}
//cell点击
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let alertController = UIAlertController(title: "提示", message: "这是第\(indexPath.row)个cell", preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
//删除功能的实现
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler: {
(action: UITableViewRowAction,indexPath: NSIndexPath) -> Void in
self.dataArr.removeObjectAtIndex(indexPath.row)
tableView.reloadData()
})
return [deleteAction]
}
}