kil*_*dos 1 uitableview uikit uiimageview uitapgesturerecognizer swift
我正在将 TapGestureRecognizer 添加到自定义 TableViewCell 处的 UIImageView,但它没有调用其操作。当我点击图像时,它会触发 tableview 的 didSelectRowAt 委托方法。我没有使用任何故事板或 .xib。我已经使用通过 .xib 创建的 UI 完成了一千次,没有任何问题,但我不明白为什么以编程方式这不起作用。任何想法?
在我的自定义 TableViewCell 处:
var favButton = UIImageView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(favButton)
configureFavButton()
}
func set(stock: Stock) {
self.stock = stock
favButton.image = UIImage(systemName: "heart.fill")?.withTintColor(.black, renderingMode: .alwaysOriginal)
}
func configureFavButton() {
// Creating constraints using SnapKit
favButton.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(10)
make.centerY.equalToSuperview()
make.height.width.equalTo(30)
}
favButton.isUserInteractionEnabled = true
favButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(removeFromFavorites)))
}
@objc func removeFromFavorites() {
guard let stock = stock else { return }
delegate?.removeFromFavorites(stock)
}
Run Code Online (Sandbox Code Playgroud)
在我的 ViewController 中,在 cellForRowAt 定义单元格时:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FavoriteCell") as! FavoriteCell
cell.delegate = self
cell.set(stock: model.favorites[indexPath.row])
return cell
}
Run Code Online (Sandbox Code Playgroud)
您需要将子视图(favButton)添加到单元格的contentView而不是视图本身
contentView.addSubview(favButton)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
600 次 |
| 最近记录: |