如何在 UITableView 中设置 UILabel 的动作
Posted
技术标签:
【中文标题】如何在 UITableView 中设置 UILabel 的动作【英文标题】:How to set action of UILabel in UITableView 【发布时间】:2017-07-13 04:13:33 【问题描述】:我在 ViewController 中有一个 UITableView,在其中有 3 个 UILabel,其中一个原型单元格标记为日期、派对和金额。现在的情况是,每当用户点击 UILabel(例如日期)时,我希望它显示特定日期的数据库表中的所有记录,或者如果用户点击了派对标签,那么将显示特定方的所有交易。所以请帮助我得到这个。我怎么能这样做..
【问题讨论】:
为什么不用UIButton代替UILabel?以及这些按钮的操作 为每个标签添加点击手势 我是 swift 或 Coding 的新手。你们可以发布示例代码来做到这一点。我不想从 UILabel 转到 UIButton。谢谢 好的,我会@Aakash 【参考方案1】:有很多人可以这样做。
您可以使用没有任何边框或背景图像的按钮。只需为按钮提供简单的文本,它看起来就像标签。为按钮添加动作。
您可以使用UIGestureRecognizers
来实现相同的目的。如@LalitKumar 所述,您可以将手势识别器直接添加到所有 UILabel 中。 .
您还可以将 Gesture Recognizer 添加到 Table View 并在 UIGesture Recognizer Action 中访问其所有子视图。
在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
【讨论】:
【参考方案2】: 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
【讨论】:
【参考方案3】:在 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!)
【讨论】:
以上是关于如何在 UITableView 中设置 UILabel 的动作的主要内容,如果未能解决你的问题,请参考以下文章
如何在 UITableView 中设置 UILabel 的动作
如何在 .xib 文件上创建的 UIViewController 中设置 UITableView
如何在 Xcode 中设置 UITableView 部分标题渐变(和透明)背景?