点击按钮时更改其不透明度 Xcode / Swift

27

我有一个带图片的UIButton,当用户按下按钮时,默认情况下图像的透明度会降低到约30%。

我想知道如何防止这种情况发生以及如何将不透明度设置为我需要的值。


可能是重复的问题:如何禁用UIButton的高亮控制状态? - ldindu
12个回答

71

如果您想以编程方式更改不透明度和时间延迟,可以在视图控制器上进行添加。

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

1
太棒了!正是我想要的——按下按钮时改变不透明度,2秒后恢复正常不透明度。谢谢! - marika.daboja
12
来自Angela Yu的Udemy Swift课程,我注意到这段代码包括了与所问问题完全无关的课程代码。播放声音与更改按钮不透明度没有任何关系。 - Henry
4
我现在正在学习这门课程。我猜我也会免费获得0.2秒的延迟时间,就像这个回答一样! - PhilCowan
3
啊,我的朋友直接从Angela Yu的Udemy课程来到了StackOverFlow。 - Aayush Shah
1
放松点,亨利,这笔交易你只需要付一份钱就能得到两个! - stromyc
嗨,亨利,原问题已经得到解答,并且他还解决了其他重要的问题,感谢你的回答。 - Afolayan Ademola

21

Swift 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
        }
    }
}

10

如果您想改变透明度,应该使用下面的代码。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
    }
}

3
你缺少一个 DispatchQueue 的闭合括号。 - Javier Heisecke

7

我不喜欢很多人提供的答案,因为它们只是模拟苹果已经为我们提供的功能,从而省略了让用户思考按钮是否在点击时更改颜色的步骤。在我看来,最佳功能应该允许按钮仅在按下时更改其不透明度,然后在未选中时恢复。在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属性自动更改其透明度!


这是一个扎实的答案,提供了100%实际应用程序用户所期望的行为。 - John Harrington

5
若要在任何时候以编程方式更改不透明度,请在AtWork中进行添加。
button.alpha = 0.30 // Make sure to use CGFloat literals
button.alpha = 1
button.alpha = 0

2

最简单的方法:

    @IBAction func keyPressed(_ sender: UIButton) {
        sender.alpha = 0.5
    }

1
      //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
    }

1
import UIKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    var player: AVAudioPlayer!

    @IBAction func keyPressed(_ sender: UIButton) {
        playAudio(sound: sender.title(for: .normal)!)
        sender.alpha = 0.5
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {sender.alpha = 1}
    }
    func playAudio(sound: String) {
        let url = Bundle.main.url(forResource: sound, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
    }
}

1

或者不使用任何 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

1

/** 这段代码是用于 Angela Yu 博士的 iOS 开发 Udemy 课程。当用户按下任何按钮时(多个按钮映射到此 IBAction 函数),此代码将播放声音,减少按钮的不透明度并等待 0.2 秒,然后增加按钮的不透明度(恢复默认值)**/

@IBAction func keyPressed(_ sender: UIButton) {
    print(sender) // This is the identity of the button that was passed by iOS to this function
    // print(sender.currentTitle)   
    playSound(soundName: sender.currentTitle!) // ! is used for null value safety

    // Challenge - changing the layer's opacity and adding a delay
    // sender.layer.opacity = 0.7 // This can be also used to change the opacity
    sender.alpha = 0.7
    // The below code uses Dispatch Queue to add a delay (from current time till 0.2 seconds passes), other methods can block the thread entirely, and the thread cannot do any other works
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
        // sender.layer.opacity = 1
           sender.alpha = 1
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接