[英]How to disable title highlight color when apply Plain style in UIButton?
我讀過這個並嘗試將類型更改為自定義,當我以舊方式配置按鈕時它有效(按鈕的樣式是默認的),但是當我應用從 iOS 15 引入的普通樣式時我可以注意到顏色改變了,是嗎禁用它的方法? 我也嘗試過adjustsImageWhenHighlighted
或showsTouchWhenHighlighted
但它們也不起作用。
您可以通過配置的.titleTextAttributesTransformer
執行此操作。
如果您在 Storyboard 中添加了一個 Plain 樣式按鈕,並且您希望標題為 - 例如 - .systemRed
且 state沒有變化,您可以這樣做:
var config = storyboardButton.configuration
// use only .systemRed for title color (in all states)
config?.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.foregroundColor = UIColor.systemRed
return outgoing
}
storyboardButton.configuration = config
代碼創建按鈕的類似方法:
var cfg = UIButton.Configuration.plain()
// use only .systemGreen for title color (in all states)
cfg.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.foregroundColor = UIColor.systemGreen
return outgoing
}
cfg.title = "Code Button"
let codeButton = UIButton()
codeButton.configuration = cfg
為了更靈活,您可以像這樣對UIButton
進行子類化:
class CustomHighlightButton: UIButton {
var normalColor: UIColor = .systemRed
var highlightColor: UIColor = .systemGreen
override func updateConfiguration() {
guard let cfg = configuration else {
return
}
var updatedCfg = cfg
let newTitleColor: UIColor
switch self.state {
case .highlighted:
newTitleColor = highlightColor
default:
newTitleColor = normalColor
}
updatedCfg.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var i = incoming
i.foregroundColor = newTitleColor
return i
}
self.configuration = updatedCfg
}
}
然后像這樣實現它:
let customButton = CustomHighlightButton()
var cfg = UIButton.Configuration.plain()
cfg.title = "Custom Highlight Button"
customButton.configuration = cfg
// use only .systemBlue for title color (in all states)
customButton.normalColor = .systemBlue
customButton.highlightColor = .systemBlue
要么:
// use .systemBlue for title color - highlighted state
customButton.highlightColor = .systemBlue
// use .systemRed for title color - all other states
customButton.normalColor = .systemRed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.