如何从类属性(尤其是UIButton)访问父类实例?

时间:2016-09-02 20:19:15

标签: ios swift uibutton

我有一个聊天气泡按钮,可以调用菜单将文本或图像复制到粘贴板。当我处理长按和双击时,我可以访问按钮本身,但是我需要能够在聊天气泡按钮旁边访问单元格实例中包含的消息属性。

我的目标是使用从action函数传递的cell.chatBubble引用来检索对单元格的引用,以便访问message数据。

func selfMessageCellForRowAtIndexPath(indexPath: NSIndexPath) -> SelfMessageCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier(SelfMessageCellIdentifier) as! SelfMessageCell

    let message = self.messages[indexPath.row]

    cell.messageLabel.text = message.messageContents
    let messageWidth = cell.messageLabel.intrinsicContentSize().width
    if messageWidth < (cell.bounds.width * 0.7 - 42) {
        cell.chatWidth = messageWidth + 33
    }

    cell.chatBubble.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleCopyGesture(_:))))

    cell.chatBubble.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(handleCopyGesture(_:))))
    let tap = UITapGestureRecognizer(target: self, action: #selector(handleCopyGesture(_:)))
    tap.numberOfTapsRequired = 2
    cell.chatBubble.addGestureRecognizer(tap)

    cell.transform = self.tableView.transform

    return cell
}


// Extension for chat bubble press handling
extension MessageSuperViewController {
func handleCopyGesture(recognizer: UIGestureRecognizer) {
    if recognizer.state == UIGestureRecognizerState.Began {
        openCopyMenu(recognizer)
    }
    else if !UIMenuController.sharedMenuController().menuVisible{
        openCopyMenu(recognizer)
    }
}

func openCopyMenu(recognizer: UIGestureRecognizer) {
    if let recognizerView = recognizer.view, recognizerSuperView = recognizer.view?.superview {
        let menuController = UIMenuController.sharedMenuController()
        let copyItem = UIMenuItem(title: "Copy", action: #selector(copyMessageContents(_:)))
        let moreItem = UIMenuItem(title: "More..", action: #selector(moreMenuItem(_:)))
        menuController.menuItems = [copyItem,moreItem]
        menuController.setTargetRect(recognizerView.frame, inView: recognizerSuperView)
        menuController.setMenuVisible(true, animated: true)
        recognizerView.becomeFirstResponder()
    }
}

func copyMessageContents(sender: UIMenuItem) {

}

func moreMenuItem(sender: UIMenuItem) {

}

1 个答案:

答案 0 :(得分:0)

我建议在UITapGestureRecognizer内添加SelfMessageCell,当您触发事件时,可以使用以下代理:

SelfMessageCellDidTapDelegate(sender: SelfMessageCell)

在此类中,selfMessageCellForRowAtIndexPath您实现了此委托,sender将包含您想要的数据。

func selfMessageCellForRowAtIndexPath(indexPath: NSIndexPath) -> SelfMessageCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier(SelfMessageCellIdentifier) as! SelfMessageCell
    cell.delegate = self
    ....
}

SelfMessageCellDidTapDelegate(sender: SelfMessageCell) {
    print(sender)
}