徽章显示在 UIButton 后面

Badge is displayed behind UIButton

我创建了一个自定义 class,它向 UIButton 添加了徽章。徽章本身是一个 UIImageView。对于每个状态,按钮可以有不同的 UI;当按钮被禁用时,它有一个清晰的背景,它显示一个边框和标题,如下图所示。

如您所见,徽章显示在边框后面,但我希望徽章位于边框之上。我试图通过将其设置为例如来调整徽章层的 zPosition 9999. 我还尝试使用 bringSubviewToFront 方法将徽章置于最前面。两种方法都不起作用。 我将徽章添加到按钮的代码是这样的:

private func addBadgeImageToButton() {
    // badgeImage is a string containing the imageName
    guard badgeImage != nil else {
        return
    }

    badgeImageView = UIImageView(image: UIImage(named: badgeImage!))

    // This line merely adjusts the position of the UIImageView
    badgeImageView!.frame = adjustedRectangleForBadge(initialSize: badgeImageView!.frame.size)

    badgeImageView!.layer.zPosition = 9999
    addSubview(badgeImageView!)

    // This line does not seem to work
    //self.bringSubviewToFront(badgeImageView!)

    // Adding these two lines won't do the trick either
    self.setNeedsLayout()
    self.layoutIfNeeded()
}

谁能帮我解决这个小问题?非常感谢任何帮助!

这是预期的行为。边框应该始终位于所有子视图之上。您可以通过在 UIButton 上添加带边框的 UIView 然后在其后添加图标来获得所需的效果。

let borderView = UIView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
borderView.layer.cornerRadius = self.layer.cornerRadius
borderView.layer.borderColor = self.layer.borderColor

// Remove the border color from the button its self
self.layer.borderColor = UIColor.clear.cgColor

// Add the border view to fake the border being there
addSubview(borderView)

// Then add the imageView on top of that border view
addSubview(badgeImageView)

尝试将徽章图像放在 xml 中的按钮之后(下方)。