Swift - RxSwift的使用詳解62 (訂閱UITableViewCell里的按鈕點(diǎn)擊事件)

我們知道通過(guò)訂閱 tableViewitemSelectedmodelSelected 這兩個(gè) Rx 擴(kuò)展方法,可以對(duì)單元格的點(diǎn)擊事件進(jìn)行響應(yīng),并執(zhí)行相關(guān)的業(yè)務(wù)代碼。

但有時(shí)我們并不需要整個(gè) cell 都能進(jìn)行點(diǎn)擊響應(yīng),可能是點(diǎn)擊單元格內(nèi)的按鈕時(shí)才觸發(fā)相關(guān)的操作,下面通過(guò)樣例演示這個(gè)功能的實(shí)現(xiàn)。

1,效果圖

(1)點(diǎn)擊單元格右側(cè)的按鈕后,會(huì)彈出顯示該單元格的內(nèi)容以及索引值。

(2)而點(diǎn)擊單元格其他位置,不觸發(fā)任何操作。

2,樣例代碼

(1)MyTableCell.swift(自定義單元格類)

注意 prepareForReuse() 方法里的 disposeBag = DisposeBag()
每次 prepareForReuse() 方法執(zhí)行時(shí)都會(huì)初始化一個(gè)新的 disposeBag。這是因?yàn)?cell 是可以復(fù)用的,這樣當(dāng) cell 每次重用的時(shí)候,便會(huì)自動(dòng)釋放之前的 disposeBag,從而保證 cell 被重用的時(shí)候不會(huì)被多次訂閱,避免錯(cuò)誤發(fā)生。

import UIKit
import RxSwift
 
//單元格類
class MyTableCell: UITableViewCell {
     
    var button:UIButton!
     
    var disposeBag = DisposeBag()
     
    //單元格重用時(shí)調(diào)用
    override func prepareForReuse() {
        super.prepareForReuse()
        disposeBag = DisposeBag()
    }
     
    //初始化
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
         
        //添加按鈕
        button = UIButton(frame:CGRect(x:0, y:0, width:40, height:25))
        button.setTitle("點(diǎn)擊", for:.normal) //普通狀態(tài)下的文字
        button.backgroundColor = UIColor.orange
        button.layer.cornerRadius = 5
        button.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        self.addSubview(button)
    }
     
    //布局
    override func layoutSubviews() {
        super.layoutSubviews()
        button.center = CGPoint(x: bounds.size.width - 35, y: bounds.midY)
    }
 
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

(2)ViewController.swift(主視圖控制器)

import UIKit
import RxSwift
import RxCocoa
 
class ViewController: UIViewController {
     
    var tableView:UITableView!
     
    let disposeBag = DisposeBag()
     
    override func viewDidLoad() {
        super.viewDidLoad()
         
        //創(chuàng)建表格視圖
        self.tableView = UITableView(frame: self.view.frame, style:.plain)
        //創(chuàng)建一個(gè)重用的單元格
        self.tableView!.register(MyTableCell.self, forCellReuseIdentifier: "Cell")
        //單元格無(wú)法選中
        self.tableView.allowsSelection = false
        self.view.addSubview(self.tableView!)
         
        //初始化數(shù)據(jù)
        let items = Observable.just([
            "文本輸入框的用法",
            "開(kāi)關(guān)按鈕的用法",
            "進(jìn)度條的用法",
            "文本標(biāo)簽的用法",
            ])
         
        //設(shè)置單元格數(shù)據(jù)(其實(shí)就是對(duì) cellForRowAt 的封裝)
        items
            .bind(to: tableView.rx.items) { (tableView, row, element) in
                //初始化cell
                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
                    as! MyTableCell
                cell.textLabel?.text = "\(element)"
                 
                //cell中按鈕點(diǎn)擊事件訂閱
                cell.button.rx.tap.asDriver()
                    .drive(onNext: { [weak self] in
                        self?.showAlert(title: "\(row)", message: element)
                    }).disposed(by: cell.disposeBag)
                 
                return cell
            }
            .disposed(by: disposeBag)
    }
     
    //顯示彈出框信息
    func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message,
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "確定", style: .cancel))
        self.present(alert, animated: true)
    }
}

RxSwift使用詳解系列
原文出自:www.hangge.com轉(zhuǎn)載請(qǐng)保留原文鏈接

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容