在 UIKit 中,自定义表格单元格内的 UIButton 是不可点击的(由于 Swift UIKit 限制?)

问题描述 投票:0回答:1

这是我的自定义单元格中的代码:

class ChatCell: UITableViewCell {
    ....
    var isSender = false {
        didSet {
            manageMessageViewLayout()
        }
    }
    
    gb = UIButton()
    gb.setImage(UIImage(named: "skejt_zelena_polutka"), for: .normal)
    gb.addTarget(self, action: #selector(matchSkateinoPressed(_:)), for: .touchUpInside)
    
    
    rb = UIButton()
    rb.setImage(UIImage(named: "skejt_crvena_polutka"), for: .normal)
    rb.addTarget(self, action: #selector(matchSkateinoPressed(_:)), for: .touchUpInside)
    
    self.isUserInteractionEnabled = true
    
    contentView.addSubview(gb)
    contentView.addSubview(rb)
    
    contentView.translatesAutoresizingMaskIntoConstraints = false
    rb.translatesAutoresizingMaskIntoConstraints = false
    gb.translatesAutoresizingMaskIntoConstraints = false
    
    contentView.heightAnchor.constraint(equalToConstant: 60).isActive = true
    
    gb.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor, constant: 0).isActive = true
    gb.widthAnchor.constraint(equalToConstant: 40).isActive = true
    gb.heightAnchor.constraint(equalToConstant: 50).isActive = true
    
    rb.leftAnchor.constraint(equalTo: gb.rightAnchor, constant: 0).isActive = true
    rb.widthAnchor.constraint(equalToConstant: 40).isActive = true
    rb.heightAnchor.constraint(equalToConstant: 50).isActive = true
    
    func manageMessageViewLayout() {
        (isSender ? rightCons : leftCons).isActive = false
        (isSender ? leftCons : rightCons).isActive = true
        
        (isSender ? rightConsContent : leftConsContent).isActive = false
        (isSender ? leftConsContent : rightConsContent).isActive = true
        
        if isSender && isChallenge {
            rb.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
            rb.leftAnchor.constraint(equalTo: contentView.rightAnchor, constant: -46).isActive = true
            
            gb.rightAnchor.constraint(equalTo: rb.leftAnchor, constant: -96).isActive = true
            gb.leftAnchor.constraint(equalTo: rb.leftAnchor, constant: -126).isActive = true
            gb.leftAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leftAnchor, constant: 0).isActive = false
        }
        
        vwContainer.backgroundColor = isChallenge ? .clear : isSender ? APP_YELLOW_COLOR : APP_LIGHT_GRAY_COLOR
        self.messageStatusImage.isHidden = isSender
    }
....
    
}

translatesAutoresizingMaskIntoConstraints
位似乎禁用了两个按钮的可点击性。我还尝试使用 MyUIButton 类扩展 UIButton,如下所示:

class MyUIButton: UIButton {
    override var canBecomeFirstResponder: Bool {
        return true
    }
}

然后将

gb = UIButton()
代码与
gb = MyUIButton()
交换 ,无济于事。为了重新获得按钮的可点击性,我在这里缺少什么?

swift uikit uibutton constraints tap
1个回答
-2
投票

您的按钮有不明确的布局,因为您没有提供足够的约束。它们具有 x 位置以及宽度和高度,但没有 y 位置。我很惊讶你甚至可以看到它们。

© www.soinside.com 2019 - 2024. All rights reserved.