如何在RxSwift中写入行的高度?

时间:2017-04-19 04:46:10

标签: ios swift3 reactive-cocoa rx-swift

我想将以下代码转换为RxSwift。另请帮助我如何在Action中编写按钮RxSwift

ReactiveCocoaRxSwift哪一种更适合在swift3中使用?

func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
Int) -> Int {
    return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
    let cell: BTSTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "BTSTableViewCellIdentifier")! as! BTSTableViewCell

    cell.configureWithPost(posts[indexPath.row])
    cell.delegate = self
    return cell

}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    // 259.5+ labelHeight+ bigImageHeight

    let postViewModel = posts[indexPath.row]

    //caption height
    var captionHeight = postViewModel.textDetail?.height(withConstrainedWidth: tableView.bounds.size.width - 20, font: UIFont.systemFont(ofSize: 17))

    captionHeight = ceil(captionHeight!)

    var finalCaptionHeight: CGFloat = 0.0;

   if postViewModel.showDetailedCaption {
        finalCaptionHeight = captionHeight!
    }
    else {
        finalCaptionHeight = min(41, captionHeight!)
    }
    return 259.5 + 
 postViewModel.getBigImageHeightFor(tableView.bounds.size.width) + 
 finalCaptionHeight

}

3 个答案:

答案 0 :(得分:4)

如果要使用RxSwift将数据绑定到tableView并想控制行/节的高度,请像这样设置UITableViewDelegate: tableView.rx.setDelegate(self).disposed(by: disposeBag)

现在您的func tableView(UITableView, heightForRowAt: IndexPath) -> CGFloat将被呼叫。

答案 1 :(得分:2)

对于RxSwift中的tableview,请看: https://github.com/devxoul/help-me-rx-tableview-cell-height/blob/master/SimpleTableViewController/SimpleTableViewController.swift

按钮操作检查下面的示例代码

button.rx.tap
        .bind { [weak self] in
            //YOUR TAP ACTION CODE LOGIC GOES HERE
        }
        .disposed(by: disposeBag)

答案 2 :(得分:0)

其他答案已过时。这是2019年带有RxSwift的Swift 4/5版本。

首先设置代表,通常在viewDidLoad中:

tableView
    .rx.setDelegate(self)
    .disposed(by: disposeBag)

然后,当然,将您的委托方法写在某个地方:

extension HostListViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
}