gpt4 book ai didi

ios - 角标(Badge)显示在 UIButton 后面

转载 作者:行者123 更新时间:2023-11-28 07:35:33 27 4
gpt4 key购买 nike

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

enter image description here

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

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()
}

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

最佳答案

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

关于ios - 角标(Badge)显示在 UIButton 后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265418/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com