[英]Listening to Swift Button Disable event
我想在禁用時將按鈕的不透明度設置為 40%。
目前我正在使用我在 StackOverflow 上找到的以下修改后的代碼:
let disabledColor = self.backgroundColor!.colorWithAlphaComponent(0.4)
self.setBackgroundImage(self.imageForColor(disabledColor), forState: .Disabled)
private func imageForColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
我想我可以在我使用的背景顏色上設置不透明度,然后簡單地從中創建一個圖像並在 .Disabled 狀態下使用它,但這沒有任何作用。
如果我將 UIColor.redColor() 之類的內容發送到 imageForColor,則按鈕在禁用時會更改為紅色……但是不透明度似乎被忽略了。
有誰知道這是為什么? 如果我可以只聽禁用事件並觸發我自己的函數,或者如果 Apple 允許我們為狀態設置背景顏色而不是背景圖像,那就太好了...
******編輯******
嘗試更多的東西,看起來它正確地應用了圖像,但它似乎將它應用於背景顏色,並且由於它是相同的顏色但具有不透明度,因此很難注意到這種變化。
我想一個解決方案是只使用背景圖像而不是顏色(?),因為我無法替換顏色......
理想情況下,我想對禁用事件的整個按鈕應用不透明度。
我認為您最好將UIButton
子類化,然后覆蓋setEnabled
以便您可以操縱背景顏色。 看到這個非常相似的線程。
這不是最好的解決方案,但為了快速,您可以更改按鈕的alpha
而不是更改btn.isUserInteractionEnabled
或btn.isEnabled
從事件隊列中刪除單擊事件。
btn.alpha = 0.5
然后在點擊事件中檢查sender.alpha
是否忽略,如下所示:
@IBAction func tapOnBtn(_ sender: UIButton) {
guard sender.alpha == 1 else { return }
//do your event here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.