如何在swift中隐藏文本为零的标签



我正在将badgeLabel添加到cartBtn中。。这里如果计数为0,我无法将整数转换为字符串,将字符串转换为整数以隐藏badgeLabel

代码:

public var badgeText: String? {
didSet {
let wasNil = NSString(string: badgeText ?? "0").integerValue <= 0
badgeLabel.isHidden = badgeText == nil
badgeLabel.text = badgeText
setSize()
if animated {
let animations: () -> Void = { [weak badgeLabel] in
badgeLabel?.layer.transform = CATransform3DMakeScale(1, 1, 1)
}
if wasNil {
badgeLabel.layer.transform = CATransform3DMakeScale(0.1, 0.1, 0.1)
}
UIView.animate(withDuration: 0.5,
delay: 0.2,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.3,
options: UIView.AnimationOptions(),
animations: animations,
completion: nil)
}
}
}
public var badgeBackgroundColor = UIColor.red {
didSet {
badgeLabel.backgroundColor = badgeBackgroundColor
}
}

像这样添加计数到标签

let cartQty = UserDefaults.standard.value(forKey: "cartCount")
cartBtn.badgeText = cartQty as? String

如果cartBtn.badgeText为零,那么我也显示badgeLabel,但如果为零,我不想显示badgeLabel。。如何做帽子。。请帮助

wasNil为true时,看起来您实际上并没有使用动画。另外,不要使用NSString,它现在是一个较旧的API,您可以使用一个简单的Int初始化器从StringInt

这里有一些更新的代码:

public var badgeText: String? {
didSet {
// changing this variable name for clarity.
let isTextAString: Bool = Int(badgeText ?? "") == nil
badgeLabel.isHidden = isTextAString
badgeLabel.text = badgeText
setSize()
if animated {
UIView.animate(withDuration: 0.5,
delay: 0.2,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.3,
options: UIView.AnimationOptions()) {
self.badgeLabel?.layer.transform = CATransform3DMakeScale(1, 1, 1)
// You can just do this `if` statement inside the animation block
if isTextAString {
self.badgeLabel.layer.transform = CATransform3DMakeScale(0.1, 0.1, 0.1)
}
} completion: { (_) in }
}
}
}

相关内容

  • 没有找到相关文章

最新更新