【问题标题】:Badge is displayed behind UIButton徽章显示在 UIButton 后面
【发布时间】:2019-04-15 08:47:20
【问题描述】:

我创建了一个自定义类,可以将徽章添加到 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()
}

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

【问题讨论】:

  • badgeImageView.superview?.bringSubviewToFront(badgeImageView)

标签: ios swift button badge zposition


【解决方案1】:

这是预期的行为。边框应该始终位于所有子视图之上。您可以通过在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)

【讨论】:

  • 这里最重要的是边框总是在子视图的顶部。这应该有效;我自己没有测试过。另一种方法是使用图像作为背景并指示切片。有关示例,请参见 stackoverflow.com/questions/12623961/…
  • 您也可以使用图像来完成此操作,但对于您的情况,我认为这比在按钮上添加另一个 UIView 更有效。使用UIView 执行此操作具有扩展到所有设备的额外好处,并且会产生更清晰的效果。在该链接中,将CAGradientLayer 添加到按钮而不是拉伸图像可能同样容易。
【解决方案2】:

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

【讨论】:

  • 问题中没有xml。
猜你喜欢
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
相关资源
最近更新 更多