Home > OS >  Can't add subview to UiButton
Can't add subview to UiButton

Time:11-09

I try to create a custom button with custom subview, but untortunately button appears without this custom subview.

public class ButtonWithSubview: UIButton {
    
    private var customView = UIView()
    
    override public init(frame: CGRect) {
        super.init(frame: .zero)
        backgroundColor = UIColor.Player.roundedButtonBackground.withAlphaComponent(0.75)
        prepareCustomView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func prepareCustomView() {
        customView.backgroundColor = UIColor.red.withAlphaComponent(0.8)
        customView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(customView)
        self.addConstraints([
            customView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            customView.leftAnchor.constraint(equalTo: self.leftAnchor),
            customView.topAnchor.constraint(equalTo: self.topAnchor),
            customView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ])
    }

}

I create this button inside a cell of UICollectionView like this:

private func prepareCustomButton() {
    customButton = ButtonWithSubview(.custom)
    customButton.setImage(UIImage(named: "play")?.resized(to: PlayerMetrics.playImageSize.value).withRenderingMode(.alwaysTemplate), for: .normal)
    customButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 0)
    customButton.translatesAutoresizingMaskIntoConstraints = false
    customButton.isUserInteractionEnabled = false
    
    contentView.addSubview(customButton)
    contentView.addConstraints([
        customButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
        customButton.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
        customButton.widthAnchor.constraint(equalToConstant: PlayerMetrics.largeButtonSize.value.width).withPriority(1000),
        customButton.heightAnchor.constraint(equalToConstant: PlayerMetrics.largeButtonSize.value.height).withPriority(1000)
    ])

}

I have no idea why custom View is not visible and actual it is not visible also in Debug View Hierarchy mode. Do you maybe have any suggestions?

CodePudding user response:

Wrap constraints inside

 NSLayoutConstraint.activate([
    // Here
 ])

Instead of self.addConstraints([---]) and contentView.addConstraints([---])

  • Related