1

我创建了一个向 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()
}

谁能帮我解决这个小问题?任何帮助是极大的赞赏!

4

2 回答 2

0

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

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)
于 2018-11-12T15:46:30.740 回答
0

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

于 2018-11-12T16:38:20.243 回答