简体   繁体   English

Swift 4. iOS 13. UITableViewCell 内的 UIButton - 如何触摸和滚动?

[英]Swift 4. iOS 13. UIButton inside a UITableViewCell - how to touch and scroll?

I am going to create a dictionary app with a list of words and their translations.我将创建一个包含单词列表及其翻译的字典应用程序。 My idea is next - when to click / touch the word (text on the UIButton) - the word will be voiced.我的想法是下一个-何时单击/触摸单词(UIButton 上的文本)-单词将被发声。 But I see the issue with scrolling the UITableView - I can scroll it only if I touch the delimiter between table rows但是我看到滚动 UITableView 的问题 - 只有当我触摸表格行之间的分隔符时,我才能滚动它

let srollView = UIScrollView()
let tableRect = CGRect(x: 0, y: 0, width: listContentWidth, height: listContentHeight)
myTableView = UITableView(frame: tableRect, style: UITableView.Style.plain)
myTableView.register(ListTableViewCell.self, forCellReuseIdentifier: cellId) //Registration of my Custom ListTableViewCell
myTableView.dataSource = self
myTableView.delegate = self
myTableView.delaysContentTouches = true;
myTableView.canCancelContentTouches = true;
srollView.addSubview(myTableView)

How to use UIButtons inside of the UITableViewCell.如何在 UITableViewCell 中使用 UIButtons。 which I create programmatically:我以编程方式创建:

class ListTableViewCell: UITableViewCell {
  private let textBtn: UIButton = {
    let btn = UIButton()
    //...
    return btn
  }()
  private let translationBtn: UIButton = {
    let btn = UIButton()
    //...
    return btn
  }()
  override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    let stackView = UIStackView(arrangedSubviews: [
        textBtn,
        translationBtn
    ])
    stackView.alignment = .fill
    stackView.distribution = .fillEqually
    stackView.axis = .horizontal
    stackView.spacing = 5
    stackView.translatesAutoresizingMaskIntoConstraints = false
    //...
    addSubview(stackView)
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

You need to add target for that button.您需要为该按钮添加目标。

textBtn.addTarget(self, action: #selector(yourFunction(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.当然,您需要设置该按钮的标签,因为您正在使用它。

textBtn.tag = indexPath.row

To get the tag in your function:要获取 function 中的标签:

@objc func yourFunction(sender: UIButton){
    let buttonTag = sender.tag
}

Some things to consider:需要考虑的一些事项:

  1. You need to add the subview to the cells contentView and not to the cell itself.您需要将子视图添加到单元格contentView而不是单元格本身。
  2. Cells are being reused: so subclass UITableViewCell and add the button to its initializer.单元格被重用:因此子类UITableViewCell并将按钮添加到其初始化程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM