一、UITableView创建(分段代码)
1、怎么创建swift的项目这里就不详细写了,直接上代码创建tableview
(1.)遵守tableview的Delegate及DataSource
class ViewController: UIViewController ,UITableViewDelegate ,UITableViewDataSource
var array = ["兔子0" ,"兔子1" ,"兔子2" ,"兔子3" ,"兔子4" ,"兔子5" ,"兔子6" ,"兔子7" ,"兔子8" ,"兔子9" ,"兔子10" ,"兔子11" ]
(2.) 创建tableview,并添加到view上
var tableView = UITableView ()
override func viewDidLoad() {
super .viewDidLoad ()
tableView = UITableView (frame: CGRectMake(0 , 64 , view.bounds .width , view.bounds .height - 64 ) ,style: UITableViewStyle.Plain )
tableView.delegate = self
tableView.dataSource = self
self .view .addSubview (tableView)
}
(3.) 实现代理方法与数据源方法
func tableView(tableView: UITableView , heightForRowAtIndexPath indexPath: NSIndexPath ) -> CGFloat {
return 60
}
func numberOfSectionsInTableView(tableView: UITableView ) -> Int {
return 1
}
func tableView(tableView: UITableView , numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(tableView: UITableView , cellForRowAtIndexPath indexPath: NSIndexPath ) -> UITableViewCell {
let initIdentifier = "Cell"
let cell = UITableViewCell (style: UITableViewCellStyle.Subtitle , reuseIdentifier: initIdentifier)
cell.textLabel ?.text = array[indexPath.row ]
cell.detailTextLabel ?.text = "baby\(indexPath.row + 1)"
cell.imageView ?.image = UIImage (named: "1024" )
return cell
}
二、全部代码
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
var array = ["兔子0" ,"兔子1" ,"兔子2" ,"兔子3" ,"兔子4" ,"兔子5" ,"兔子6" ,"兔子7" ,"兔子8" ,"兔子9" ,"兔子10" ,"兔子11" ]
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let initIdentifier = "Cell"
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle , reuseIdentifier: initIdentifier)
cell.textLabel ?.text = array[indexPath.row ]
cell.detailTextLabel ?.text = "baby\(indexPath.row + 1)"
cell.imageView ?.image = UIImage(named: "1024" )
return cell
}
var lableTitle = UILabel()
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad ()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView(frame: CGRectMake(0 , 64 , view.bounds .width , view.bounds .height - 64 ) ,style: UITableViewStyle.Plain )
tableView.delegate = self
tableView.dataSource = self
self.view .addSubview (tableView)
lableTitle = UILabel()
lableTitle.text = "TableView"
lableTitle.textColor = UIColor .redColor ()
lableTitle.textAlignment = NSTextAlignment.Center
lableTitle.frame = CGRectMake(0 , 0 , view.bounds .width , 64 )
lableTitle.backgroundColor = UIColor .grayColor ()
self.view .addSubview (lableTitle)
}
}
三、上一个预览图