开发环境:IOS8.0+ Swift 2.3
创建UITableViewCell
记得要选择:Also create XIB file
填写Identifier
填写Identifier,这个会在后面用到
完成XIB的布局和约束
连线
创建按钮点击的协议
protocol CouponTableViewCellDelegate {
func couponBtnClick(couponID:Int!)
}
算了,直接上代码吧
import UIKit
class CouponTableViewCell: UITableViewCell {
@IBOutlet weak var lbSender: UILabel!
@IBOutlet weak var lbPrice: UILabel!
@IBOutlet weak var lbDate: UILabel!
//优惠券ID
var couponID:Int!
var delegate:CouponTableViewCellDelegate!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func btnClick(sender: UIButton) {
delegate.couponBtnClick(couponID)
}
}
//
protocol CouponTableViewCellDelegate {
func couponBtnClick(couponID:Int!)
}
在TableCell中的点击事件,使用协议中的方法,注意,cell调用时需要给delegate赋值
调用
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CouponTableViewCellDelegate {
@IBOutlet weak var tv: UITableView!
var couponList = [["id" : "1", "sender" : "ladeng", "price" : "100", "date" : "2017-01-11"],
["id" : "2", "sender" : "book", "price" : "102", "date" : "2017-02-21"],
["id" : "3", "sender" : "feek", "price" : "110", "date" : "2018-11-11"]]
override func viewDidLoad() {
super.viewDidLoad()
tv.dataSource = self
tv.delegate = self
//couponTableViewCell就是前面填写的
tv.registerNib(UINib(nibName: "CouponTableViewCell", bundle: nil), forCellReuseIdentifier: "couponTableViewCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return couponList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let d = couponList[indexPath.row]
//couponTableViewCell就是前面填写的
let cell = tableView.dequeueReusableCellWithIdentifier("couponTableViewCell", forIndexPath: indexPath) as! CouponTableViewCell
cell.couponID = NSString(string: d["id"]!).integerValue
cell.lbSender.text = d["sender"]
cell.lbPrice.text = d["price"]
cell.lbDate.text = d["date"]
//这个千万别忘了
cell.delegate = self
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
func couponBtnClick(couponID: Int!) {
print(couponID)
}
}
写的比较粗糙啊