我嘗試使用自定義子視圖創建自定義按鈕,但不幸的是,按鈕出現時沒有此自定義子視圖。
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)
])
}
}
我在 UICollectionView 的單元格中創建了這個按鈕,如下所示:
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)
])
}
我不知道為什么自定義視圖不可見,實際上它在除錯視圖層次結構模式下也不可見。你有什么建議嗎?
uj5u.com熱心網友回復:
在內部包裝約束
NSLayoutConstraint.activate([
// Here
])
而不是self.addConstraints([---])和contentView.addConstraints([---])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/530618.html
