【问题标题】:UIButton's .touchUpInside event not workingUIButton 的 .touchUpInside 事件不起作用
【发布时间】:2019-12-04 23:05:49
【问题描述】:

我正在努力在运行时向UICollectionViewCell 添加按钮,并在运行时根据其类型将按钮注册到事件中。按钮的类型可以是,例如,话语按钮和动作按钮,两者都应该注册到单独的事件中。

UI 元素的层次结构类似于UICollectionView -> UICollectionViewCell -> StackView -> 多个 (UIView -> UIButton)。

问题是我无法注册.touchUpInside 事件。

我尝试过的是通过按钮实例调用becomeFirstResponder(),在UIViewController 中移动事件方法,并在设置视图层次结构后在cellForItemAt 方法中添加目标,尝试isUserInteractionEnabled 值@987654332 @ 和 falseUICollectionViewUICollectionViewCellUIStackViewUIViewUIButton 上。

编辑 1: 所以代码如下所示:

class AssistantViewController: UIViewController {
    private var assistantManager: AssistantManager
    private var conversationSection: UICollectionView
    private let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()

    private var multipleChoiceMessageCell = MultipleChoiceMessageCell()
    private var conversationCells: [BaseCollectionViewCell] {
        return [
            multipleChoiceMessageCell
        ]
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        construct()
        assistantManager.performGreetingUtterance()
    }

}

extension AssistantViewController: UICollectionViewDataSource {
    @objc func didTapUtteranceButton() {
        print ("elo I a m here")
    }

    func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> 
  UICollectionViewCell {
        let conversationItem = assistantManager.conversationItems[indexPath.row]
        let cellId = self.getCellIdentifier(for: conversationItem)
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId,
                                                      for: indexPath) as? ConversationItemCell

        if let conversationCell = cell {
            conversationCell.layoutIfNeeded()

            conversationCell.configure(with: conversationItem)

            switch conversationItem {
            case let .multipleChoiceMessage(chatMessage, multipleChoice): do {

                for item in multipleChoice.multipleChoice.items {
                    switch item {
                    case .utteranceButton(let utteranceButton): do {
                        utteranceButton.button.isUserInteractionEnabled = true
                        utteranceButton.button.addTarget(self,
                                                         action: #selector(didTapUtteranceButton),
                                                         for: .touchUpInside)
                        //utteranceButton.button.becomeFirstResponder()
                        print("added")
                        }
                    }
                }
                }
            default: print("Todo")
            }
        }
        return cell!
    }

class AssistantManager {
    public func parseAssistantSnippets(
        snippets: [Snippet]) -> ConversationCellModel {
        var interactableItems: [MessageContent] = []
        var utteredText:String = ""

        for snippet in snippets {
            switch snippet {
            case .text(let text): utteredText = text.displayText
            case .utteranceButton(let utteranceButton): do {
                let button = UtteranceButton(buttonTitle: utteranceButton.displayText,
                                               maxWidth: ConversationCell.elementMaxWidth,
                                               utteranceText: utteranceButton.utteranceText,
                                               onPress: performUserUtterance)
                let messageContent = MessageContent.utteranceButton(button)

                interactableItems.push(messageContent)
                }
            default: print("TODO")
            }
        }
        return  ConversationCellModel.init(message: utteredText,
                                           multipleChoice: interactableItems)
    }

    public func performGreetingUtterance() {
        self.addTypingIndicator()

        performUtteranceOperation(utterance: "hi")
    }

    public func performUtteranceOperation(utterance: String) {
        let context = UtteranceRequest.UserContext(cid: "1",
                                                   location: CLLocationCoordinate2D(),
                                                   storeID: "1",
                                                   timeZoneOffset: 0)
        let request = UtteranceRequest(utterance: utterance,
                                       context: context)

        provider.conveyUtterance(request) { [weak self] result in
            switch result {
            case .success(let snippetResponse): do {
                let snippetResponseTransformed = SnippetResponse.init(snippetResponse)
                let ConversationCellModel = self?.parseAssistantSnippets(
                    snippets: snippetResponseTransformed.snippets)

                if let model = ConversationCellModel {
                    self?.addMessageFromAssistant(interactableItems: model.multipleChoice,
                                                       utteredText: model.message)
                }
                }
            case .failure(let error): return
            }
        }
    }
}

class MultipleChoiceMessageCell: ConversationCell {
    public func configure(with conversationItem: ConversationItem) {
        switch conversationItem {
        case let .multipleChoiceMessage(chatMessage, multipleChoice): do {
            let isCellFromUser = chatMessage.metadata.isFromUser
            let avatarBackgroundColor = chatMessage.metadata.avatarBackgroundColor
            let avatarTintColor = chatMessage.metadata.avatarTintColor
            let messageTextBackgroundColor = chatMessage.metadata.textContainerBackgroundColor
            let messageTextColor = chatMessage.metadata.textColor

            self.messageTextLabel.text = chatMessage.message
            self.avatarImageView.image = chatMessage.metadata.avatarImage
            self.messageTextContainer.backgroundColor = messageTextBackgroundColor
            self.messageTextLabel.textColor = messageTextColor
            self.avatarImageView.backgroundColor = avatarBackgroundColor
            self.avatarImageView.tintColor = avatarTintColor
            self.rightMessageHorizontalConstraint?.isActive = isCellFromUser
            self.leftMessageHorizontalConstraint?.isActive = !isCellFromUser
            self.rightAvatarHorizontalConstraint?.isActive = isCellFromUser
            self.leftAvatarHorizontalConstraint?.isActive = !isCellFromUser

            configureCellWith(interactablesSection: multipleChoice.multipleChoice.itemsContainer)
        }
        default:
            logIncorrectMapping(expected: "message", actual: conversationItem)
        }
    }

    func configureCellWith(interactablesSection: UIStackView) {
        let stackViewTop = NSLayoutConstraint(
            item: interactablesSection,
            attribute: .top,
            relatedBy: .equal,
            toItem: self.messageTextContainer,
            attribute: .bottom,
            multiplier: 1,
            constant: 10)
        let stackViewLeading = NSLayoutConstraint(
            item: interactablesSection,
            attribute: .leading,
            relatedBy: .equal,
            toItem: self,
            attribute: .leading,
            multiplier: 1,
            constant: ConversationCell.avatarMaxSize +
                ConversationCell.messageContainerMaxLeadingMargin +
                ConversationCell.avatarMaxMargin)

        self.addAutoLayoutSubview(interactablesSection)

        self.addConstraints([stackViewTop,
                             stackViewLeading])
    }
}

class InteractableItem {
    let contentView: UIView
    var height: CGFloat

    init() {
        contentView = UIView()
        height = 0
    }
}

class CellPrimaryButton: InteractableItem {
    let button: CorePrimaryButton

    init(buttonTitle titleLabel: String, maxWidth: CGFloat) {
        button = CorePrimaryButton()
        button.setTitle(titleLabel, for: .normal)
        button.setBackgroundColor(CoreColor.white, for: .normal)
        button.setTitleColor(CoreColor.black, for: .normal)
        button.layer.borderColor = CoreColor.black.cgColor
        button.layer.borderWidth = 1
        //button.becomeFirstResponder()
        super.init()
        contentView.isUserInteractionEnabled = true
//        button.addTarget(self, action: #selector(didTapUtteranceButton), for: .touchUpInside)
        setConstraints(maxWidth: maxWidth)
    }

    func setConstraints(maxWidth: CGFloat) {
        let buttonHorizontal = NSLayoutConstraint(item: self.button,
                                                  attribute: .leading,
                                                  relatedBy: .equal,
                                                  toItem: self.contentView,
                                                  attribute: .leading,
                                                  multiplier: 1,
                                                  constant: 0)

        let buttonWidth = NSLayoutConstraint(item: self.button,
                                              attribute: .width,
                                              relatedBy: .lessThanOrEqual,
                                              toItem: nil,
                                              attribute: .notAnAttribute,
                                              multiplier: 1,
                                              constant: maxWidth)

        self.contentView.addConstraints([buttonHorizontal,
                                         buttonWidth])
        self.contentView.backgroundColor = UIColor.purple
        self.height = self.button.intrinsicContentSize.height
        self.contentView.addAutoLayoutSubview(self.button)
    }
}

class UtteranceButton: CellPrimaryButton {
    let utteranceText: String
    let performUtterance: (String) -> Void

    init(buttonTitle titleLabel: String,
         maxWidth: CGFloat,
         utteranceText: String,
         onPress: @escaping (String) -> Void) {

        self.utteranceText = utteranceText
        self.performUtterance = onPress

        super.init(buttonTitle: titleLabel, maxWidth: maxWidth)
    }
}

【问题讨论】:

  • 单元格在视图中是否正确显示?如果您将isUserInteractionEnabled 设置为true,那么您在触摸UIButton 时是否有视觉反馈?如果你把它设置为 false 你还有吗?如果将目标移动到UICollectionViewCell 是否有效?
  • @André 是的,单元格在视图中正确显示。不,UIButton 在这两种情况下都不提供视觉反馈。不,如果将目标移动到UICollectionViewCell,它将不起作用。我还尝试了UICollectionViewDataSourcedidSelectItemAt 方法,每次都会调用它。所以我的猜测是单元格干扰了按钮的输入,但是如何禁用这种行为呢?
  • @André 另外,UIViewController 中的UIView 下方有一个发言按钮,它可以正常工作。所以UIViewController应该没有问题。问题基本上出在UICollectionView 的孩子身上。
  • @André 如果我将isUserInteractionEnabled 设为false,则不会调用didSelectItemAt
  • 对。我建议您创建一个简单的UICollectionViewCell 并在其中插入一个简单的UIButton 以查看它是否有效。从您的层次结构中再插入一个元素,测试并查看它是否仍然有效。这样做直到你发现问题出在哪里。但我不得不说,你做事的方式看起来并不传统。

标签: ios swift uicollectionview uibutton touch-up-inside


【解决方案1】:

试试这种调用动作的方式。

UIApplication.shared.sendAction(#selector(didTapUtteranceButton), to: self, from: nil, for: nil)

而不是这个:

utteranceButton.button.addTarget(self, #selector(didTapUtteranceButton), for: .touchUpInside)

【讨论】:

  • 我发现了一个奇怪的现象。我用添加按钮和事件的相同方法创建了另一个项目,它工作正常。可能是这个特定项目中的其他问题。我目前正在从事其他一些项目,稍后也会尝试一下。顺便谢谢:)
猜你喜欢
  • 2016-08-21
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多