如何在UITableView中设置UILabel的动作

时间:2017-07-13 04:13:34

标签: ios iphone uitableview swift3

我在ViewController中有一个UITableView,其中有一个UILabel,其中一个原型单元标记为Date,Party和Amount。现在的情况是,我希望每当用户点击UILabel时,比如Date,它会显示特定日期的数据库表中的所有记录,或者如果用户点击了Party Label,那么将显示特定方的所有交易。所以请帮我解决这个问题。我怎么能这样做..

3 个答案:

答案 0 :(得分:2)

有许多人也这样做。

  1. 您可以使用没有任何边框或背景图像的按钮。只需将简单文本提供给按钮,它就像标签一样。向按钮添加操作。

  2. 您可以使用UIGestureRecognizers。您可以按照@LalitKumar的说明直接将Gesture Recognizer直接添加到所有UILabel。 。

  3. 您还可以在表格视图中添加手势识别器,并在您的UIGesture识别器操作中访问其所有子视图。

  4. viewDidLoad中添加手势识别器

        let tap = UITapGestureRecognizer(target: self, action: #selector(Yourcontroller.handleTap))
        yourTableView.isUserInteractionEnabled = true
        yourTableView.addGestureRecognizer(tap)
    

    定义手势识别器的操作并获取单元格的索引路径以及单元格的子视图。

    func handleTap(_ gesture: UITapGestureRecognizer){
         let tapLocation = gesture.location(in: self.tableView)
         if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) 
         {
             if let tappedCell = self.tableView.cellForRow(at: tapIndexPath) as? UITableViewCell 
              {
                 print("Row Selected") // access tapped cell and its subview as
                 let touchpoint:CGPoint = gesture.location(in: cell)
    
                     if cell.datelabel.frame.contains(touchpoint)  {
                           // user tapped date label
                         } elseif cell.imageView.frame.contains(touchpoint) {
                           // user tapped image
                     }
              }
          }
     }
    

答案 1 :(得分:0)

   let tap = UITapGestureRecognizer(target: self, action: #selector(Yourcontroller.tapLabelFunction))
   yourLabel.isUserInteractionEnabled = true
   yourLabel.addGestureRecognizer(tap)

 // if you make label on the cell
    cell.yourLabel.userInteractionEnabled = true
    cell.yourLabel.tag = indexPath.row
    cell.yourLabel.addGestureRecognizer(tap)

}

 func tapLabelFunction(sender:UITapGestureRecognizer) {

    print("label tapped",sender.view!.tag); // for tag

}

答案 2 :(得分:0)

在cellForRowAtIndexPath

中添加
yourLabel?.isUserInteractionEnabled = true
if ((yourLabel?.gestureRecognizers?.description) == nil) {
                let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tap(onPeopleName:)))
                tapGesture.delegate = self
                tapGesture.numberOfTapsRequired = 1
                tapGesture.numberOfTouchesRequired = 1
                tapGesture.cancelsTouchesInView = false
                yourLabel?.addGestureRecognizer(tapGesture)
            }

<强>选择

func tap(onPeopleName gesture: UIGestureRecognizer) {
        let lbl: UILabel? = (gesture.view as? UILabel)
        let cell: UITableViewCell? = (lbl?.superview?.superview as? UITableViewCell)
        let indexPath: IndexPath? = tblViewPracticeDetail.indexPath(for: cell!)
}