[英]changing opacity of button when clicked xcode / swift
我有一个带有图像的 UIButton 设置,默认情况下,当用户按下按钮时,图像的不透明度会降低到 30% 左右。
我想知道如何防止这种情况发生以及如何将不透明度设置为我需要的任何值。
添加视图控制器,如果您想以编程方式更改不透明度和时间延迟。
@IBAction func keyPressed(_ sender: UIButton) {
playSound(soundName: sender.currentTitle!)
//Reduces the sender's (the button that got pressed) opacity to half.
sender.alpha = 0.5
//Code should execute after 0.2 second delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//Bring's sender's opacity back up to fully opaque.
sender.alpha = 1.0
}
}
func playSound(soundName: String) {
let url = Bundle.main.url(forResource: soundName, withExtension: "wav")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}
斯威夫特 5
您可以通过使用DispatchQueue来做到这一点。 更重要的是,要使过渡“平滑”,请使用UIView.animate 。
只需更改 alpha 参数。
@IBAction func keyPressed(_ sender: UIButton) {
sender.alpha = 0.5
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3 ) {
sender.alpha = 1.0
}
}
参数的平滑变化。
@IBAction func keyPressed(_ sender: UIButton) {
UIView.animate(withDuration: 0.3) {
sender.alpha = 0.5
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3 ) {
UIView.animate(withDuration: 0.3) {
sender.alpha = 1.0
}
}
}
如果你想改变不透明度,你应该使用下面的代码。 alpha 基本上是不透明度。 您实际上可以更改底部部分时间,例如您希望它变暗的时间,您还可以更改 sender.alpha 值,例如您希望它变暗的程度。
@IBAction func keyPressed(_ sender: UIButton)
{
//Reduces the sender's (the button that got pressed) opacity to half.
sender.alpha = 0.5
//Code should execute after 0.2 second delay.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//Bring's sender's opacity back up to fully opaque.
sender.alpha = 1.0
}
}
添加到 AtWork,如果您想随时以编程方式更改不透明度。
button.alpha = 0.30 // Make sure to use CGFloat literals
button.alpha = 1
button.alpha = 0
最简单的方法:
@IBAction func keyPressed(_ sender: UIButton) {
sender.alpha = 0.5
}
我不喜欢这些答案中的很多,因为它们的快捷方式使用户认为按钮在点击时会改变颜色,但只是模仿了苹果已经为我们提供的功能。 在我看来,最佳功能将允许按钮仅在按下时更改其不透明度,然后在未选择时恢复。 在 Swift 5 中试试这个:
1)创建一个名为SomeCustomBtn
的新 swift 文件
2)插入此代码:
import UIKit
class SomeCustomBtn: UIButton {
override open var isHighlighted: Bool {
didSet {
alpha = isHighlighted ? 0.5 : 1.0
}
}
}
3)将您的自定义类添加到您的按钮,iOS 将根据属性isHighlighted
自动更改您的 alpha !
//Reduces the opacity of the Button to half (the selected Button)
sender.alpha = 0.5
//this line of code will help you to delay the opacity to the selected seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//This code brings sender's opacity back to fully opaque.
sender.alpha = 1.0
}
或者一种简单的方法是不使用任何DispatchQueue
是这样的:
@IBAction func KeyDownPressed(_ sender: UIButton) {
sender.alpha = 0.5
}
@IBAction func keyPressed(_ sender: UIButton) {
sender.alpha = 1
playSound(col : sender.currentTitle!)
}
请注意:将func KeyDownPressed
的动作事件设置为Touch Down
您可以简单地将adjustImageWhenHighlighted设置为No 。
button.adjustsImageWhenHighlighted = NO;
如果它不适合您,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.