【问题标题】:How to fade in the entire UIButton instead of just title when tapped?点击时如何淡入整个 UIButton 而不仅仅是标题?
【发布时间】:2021-12-25 08:39:55
【问题描述】:

所以我有以下按钮,点击时只会向标题添加淡入淡出动画。我希望淡入淡出动画发生在整个按钮中。我怎样才能做到这一点?谢谢!

import UIKit

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    
    let button = UIButton(type: .system)
    button.setTitle("Btn", for: .normal)
    button.backgroundColor = .systemBlue
    button.tintColor = .white
    
    view.addSubview(button)
    
    button.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
      button.heightAnchor.constraint(equalToConstant: 60.0),
      button.widthAnchor.constraint(equalToConstant: 60.0),
      button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      button.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    ])
  }
}

【问题讨论】:

  • 在按钮动作上添加简单的淡入淡出动画。
  • 哦,所以按钮的淡入淡出动画不是内置的? @RTXGamer
  • 是的,只有文本部分闪烁,您可以使用showsTouchWhenHighlighted 来获得触摸发光效果。

标签: ios swift uikit


【解决方案1】:

您可以尝试将 addTarget 与 objc 函数一起使用:

@objc func buttonTapped(_ sender: UIButton){
    print("buttonTapped")
     sender.alpha = 0.5
     DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
         sender.alpha = 1.0
     }
}

通过以下方式执行:

    button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2018-07-23
    • 2015-03-02
    • 2023-03-09
    相关资源
    最近更新 更多