我想将以下代码转换为RxSwift
。另请帮助我如何在Action
中编写按钮RxSwift
。
ReactiveCocoa
或RxSwift
哪一种更适合在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
}
答案 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
}
}