【问题标题】:Swift - UIButton not highlighted while pressedSwift - 按下时 UIButton 未突出显示
【发布时间】:2020-05-06 20:51:15
【问题描述】:

以编程方式添加UIButton 时遇到问题。没有“点击动画”。

有谁知道为什么会发生这种情况以及如何解决这个问题?我找不到有关此主题的任何内容...

let weiterButton: UIButton = {
    let v = UIButton()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.setTitle("WEITER", for: .normal)
    v.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 20)
    v.titleLabel?.textColor = .white
    v.backgroundColor = UIColor(red: 75/255, green: 75/255, blue: 75/255, alpha: 1)
    v.addTarget(self, action: #selector(weiterButtonTapped), for: .touchUpInside)
    return v
}()

我想要的动画:

Animation

【问题讨论】:

  • 您是否尝试为突出显示/按下的状态应用颜色?
  • 没有。我只想要标准的点击动画。添加backgroundImage 时似乎可以正常工作,但我也想要没有image 的动画 ..
  • @TejaNandamuri 是对的。您需要为突出显示的状态添加自定义文本颜色,例如只需添加这一行v.setTitleColor(.red, for: .highlighted)
  • 但应该更改backgroundColor 而不是TitleColor
  • @AlexSmet 我用视频更新了我的问题

标签: ios swift animation uibutton


【解决方案1】:

您必须设置lazy var 而不是let,因为您想摆脱变量(按钮)。此外,您必须设置UIButton(type: .system),因为您告诉该按钮应该具有某种样式。

lazy var weiterButton: UIButton = {
    let v = UIButton(type: .system)
    v.translatesAutoresizingMaskIntoConstraints = false
    v.setTitle("WEITER", for: .normal)
    v.titleLabel?.font = UIFont(name: "AvenirNext-Bold", size: 20)
    v.setTitleColor(.white, for: .normal)
    // If you want a different color when it is pressed
    v.setBackgroundImage(UIImage(named: "Hlighlighted image"), for: .highlighted)
    v.setBackgroundImage(UIImage(named: "Your image"), for: .normal)
    v.addTarget(self, action: #selector(weiterButtonTapped), for: .touchUpInside)
    return v
}()

【讨论】:

  • 将其更改为 lazy var 没有做任何事情
  • 这很奇怪。你有@objc 函数吗?
  • 是的,它正在正常工作。我和其他UIButtons 也有这个问题
  • 你的 ViewController 是不是有问题?
  • 您提到其他 UIButton 效果不佳。您的按钮是在同一个 ViewController 中还是在另一个 ViewController 中?
猜你喜欢
  • 2017-05-15
  • 1970-01-01
  • 2020-08-22
  • 2017-05-20
  • 2011-09-14
  • 1970-01-01
  • 2019-11-30
  • 2018-09-22
  • 1970-01-01
相关资源
最近更新 更多