swift UIButton可见背景

s4n0splo  于 2023-02-18  发布在  Swift
关注(0)|答案(1)|浏览(118)

找不到关于UIButton上自定义视图字段的任何有用信息我需要创建一个UIButton的子类,它具有大按钮框架和小可见部分,我还需要在按钮点击时设置动画背景,因此我需要将按钮背景设置为backgroundImage
下面是我的代码:

public final class BigSmallButton: UIButton {
...

public override var buttonType: UIButton.ButtonType {
    return .custom
}

override init(frame: CGRect) {
    super.init(frame: frame)

    NSLayoutConstraint(item: self,
                       attribute: .height,
                       relatedBy: .equal,
                       toItem: nil,
                       attribute: .notAnAttribute,
                       multiplier: 1.0,
                       constant: 44).isActive = true

    let imageSize = CGSize(width: 24, height: 24)
    let backgroundImage = UIImage.image(with: Constants.buttonBackgroundColor, size: imageSize)
    setBackgroundImage(backgroundImage, for: .normal)

    layer.cornerRadius = Constants.buttonIconSize.height / 2.0
    layer.masksToBounds = true
    
    layer.frame = CGRect(x: 0, y: 0, width: bounds.width, height: imageSize.height)
}

然后添加到NavigationController

let bigSmallButton = BigSmallButton(frame: .zero)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: bigSmallButton)

它工作,但我的按钮高度变为等于24.0而不是44.0
我想知道做这样的纽扣有可能吗?
如果这是可能的,那我做错了什么?

cygmwpex

cygmwpex1#

我发现的唯一方法是覆盖按钮函数point(inside point: CGPoint, with event: UIEvent?)
大概是这样的

let hitFrame: CGRect

    override init(frame: CGRect) {
        super.init(frame: frame)

        hitFrame = CGRect(x: frame.minX, y: frame.minY - 10.0, width: frame.width, height: frame.height + 10.0)
    }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        return hitFrame.contains(point)
    }

相关问题