swift第一個iOS專案 純程式碼程式設計(續)
class MyViewController: UIViewController, UITableViewDelegate,UITableViewDataSource
向tableview中填充資料
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return dataSource.count;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style:UITableViewCellStyle
let object = dataSource[indexPath.row] as NSDictionary
println(object)
// cell.shouldIndentWhileEditing = true
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.textLabel.text = object["title"] as? String
cell.detailTextLabel
cell.imageView.image = UIImage(named :"defaultphotoS")
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
let request = NSURLRequest(URL: NSURL(string: object["thumb"] as String)!)
NSURLConnection.sendAsynchronousRequest(request, queue: thumbQueue, completionHandler: { response, data, error in
if (error != nil) {
println(error)
} else {
let image = UIImage.init(data :data)
dispatch_async(dispatch_get_main_queue(), {
cell.imageView.image = image
})
}
})
return cell
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 80
}
下一步就要設定點選cell進入新聞詳情頁了
這裡需要說明的是新聞詳情的資料是要根據新聞id號來獲取的,當然這些在做具體專案的時候看介面文件就明白了
那麼這裡點選cell需要將新聞id號傳過去,而新聞id號就存在先前請求的新聞列表的資料中,這裡獲取下傳值到下一個viewcontroller就行了
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
var web = NewsViewController()
let object = dataSource[indexPath.row] as NSDictionary
let id = object["id"] as String
let a = id.toInt()
web.detailID = a!
self.navigationController?.pushViewController(web, animated: true)
}
這裡NewsViewController就是我們要建立的新聞詳情的頁面了,建立一個ViewController,命名為NewsViewController裡面設定個detailId來接收傳過來得id值,添加個webview用來顯示新聞詳情
var detailID = NSInteger()
var webView:UIWebView?
在viewDidLoad()中override func viewDidLoad() {
super.viewDidLoad()
self.webView = UIWebView(frame:self.view.frame)
self.title = "新聞中心"
self.loadData()
self.view.addSubview(self.webView!)
// Do any additional setup after loading the view.
}
根據detailID的值來請求新聞詳情資料,並載入到webview中這裡要注意的是,demo中提供得介面返回的新聞詳情是html資料,所以可以用webview載入,如果請求返回的是別的資料請自行做處理顯示
func loadData(){
var urlStr = "http://qingbin.sinaapp.com/api/html/\(detailID).html"
println(urlStr)
var url = NSURL(string: urlStr)
var urlRequest = NSURLRequest(URL :url!)
self.webView!.loadRequest(urlRequest)
}
好了,這裡就完成了,點選執行就可以看到前面得效果,算是一個小demo了。是不是很簡單。