How to detect tap on Uitableview cell with uiview and uibutton?

后端 未结 3 2016
南方客
南方客 2021-01-25 22:12

I have created a table view and i am adding my custom uiview into the cell\'s content view. The uiview has a uibutton. However i can add the uibutton into the content view when

3条回答
  •  长发绾君心
    2021-01-25 22:26

    You could subclass UITableViewCell and add a button, here is an example class:

    import UIKit
    
    private let DWWatchlistAddSymbolCellAddSymbolButtonLeftMargin: CGFloat = 15
    
    class DWWatchlistAddSymbolCell: UITableViewCell {
    
      private(set) var addSymbolButton:UIButton
    
      init(reuseIdentifier:String?, primaryTextColor:UIColor) {
        self.addSymbolButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        super.init(style:UITableViewCellStyle.Default, reuseIdentifier:reuseIdentifier)
        selectionStyle = UITableViewCellSelectionStyle.None
        backgroundColor = UIColor.clearColor()
        imageView!.image = UIImage(named:"PlusIcon")!
        addSymbolButton.setTitle("Add Symbol", forState:UIControlState.Normal)
        addSymbolButton.setTitleColor(primaryTextColor, forState:UIControlState.Normal)
        addSymbolButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
        addSymbolButton.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
        contentView.addSubview(addSymbolButton)
      }
    
      required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
      }
    
      // MARK: Layout
    
      override func layoutSubviews() {
        super.layoutSubviews()
        addSymbolButton.frame = contentView.frame
        let imageViewFrame = imageView!.frame
        let imageViewMaxX = imageViewFrame.origin.x + imageViewFrame.size.width
        let addSymbolButtonX = imageViewMaxX + DWWatchlistAddSymbolCellAddSymbolButtonLeftMargin
        addSymbolButton.contentEdgeInsets = UIEdgeInsetsMake(0, addSymbolButtonX, 0, 0);
      }
    }
    

    You can see the "Add Symbol" button at the bottom:

                                           Add Symbol Button Cell

    When you're returning the cell for the UITableViewDataSource, make sure to set the target for the button:

    private func addButtonCell(tableView: UITableView) -> UITableViewCell {
      var cell:DWWatchlistAddSymbolCell? = tableView.dequeueReusableCellWithIdentifier(kDWWatchlistViewControllerAddButtonCellReuseIdentifier) as? DWWatchlistAddSymbolCell
      if (cell == nil) {
        cell = DWWatchlistAddSymbolCell(reuseIdentifier:kDWWatchlistViewControllerAddButtonCellReuseIdentifier, primaryTextColor:primaryTextColor)
      }
      cell!.addSymbolButton.addTarget(self,
        action:Selector("didPressAddSymbolButton"),
        forControlEvents:UIControlEvents.TouchUpInside)
      return cell!
    }
    

提交回复
热议问题