//
// ViewController.swift
// swiftNew
//
// Created by mibo02 on 17/1/4.
// Copyright ? 2017年 mibo02. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
let btnStartTag:Int = 1000//定義btn的tag起始值
let name_links_tuples:[(String,String)] = [
("第一個(gè)","峰峰"),
("第二個(gè)","小明"),
("第三個(gè)","小王")
]
let table:UITableView = UITableView.init(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
override func viewDidLoad() {
super.viewDidLoad()
//添加到view上
self.view.addSubview(table)
//遵守協(xié)議
table.dataSource = self
table.delegate = self
}
//實(shí)現(xiàn)協(xié)議中的方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return name_links_tuples.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: nil)
let newtitle:String = name_links_tuples[indexPath.row].0
//每一行有一個(gè)下載的按鈕
let btn:UIButton = UIButton.init(type: UIButtonType.custom)
btn.frame = CGRect(x:UIScreen.main.bounds.width - 100, y:10, width:80, height:50)
btn.backgroundColor = UIColor.red
btn.setTitle("下載", for: UIControlState.normal)
btn.setTitleColor(UIColor.black, for: UIControlState.normal)
btn.tag = indexPath.row + btnStartTag
btn.addTarget(self, action:#selector(clickBtnAction), for:.touchUpInside)
cell.textLabel?.text = newtitle
cell.contentView.addSubview(btn)
return cell
}
//table的cell的高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
func clickBtnAction(sender:UIButton) {
print("....")
let indexOfBtn:Int = sender.tag - btnStartTag
if indexOfBtn >= 0 && indexOfBtn < name_links_tuples.count {
let str = name_links_tuples[indexOfBtn].1
let url = NSURL(string:str)
if url != nil {
UIApplication.shared.open(url as! URL, options: [:], completionHandler: nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//值得注意的一點(diǎn)是,button的點(diǎn)擊事件,無(wú)論帶不帶參數(shù),寫(xiě)的時(shí)候都不需要加 : 直接將方法名寫(xiě)上即可。
//還有一點(diǎn)就是沒(méi)想到frame的寫(xiě)法已經(jīng)變成了這樣。
屏幕快照 2017-01-04 下午2.34.50.png