[英]UIButton's backgroundImage's content mode not respected
我正在對我即將發布的應用程序進行最后潤色,但我遇到了讓UIButton
的背景圖像的contentMode
受到尊重的困難。 無論我指定的contentMode
什么,圖像都會在背景中被撲通一聲而不考慮contentMode
設置。
我看過一篇關於這個主題的帖子,但在我的情況下它似乎沒有做任何事情。
這是從viewDidLoad
調用的:
// I tried putting the contentMode lines here...
myButton.imageView!.contentMode = .scaleAspectFit
myButton.contentMode = .scaleAspectFit
myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)
// ...and here
// myButton.imageView!.contentMode = .scaleAspectFit
// myButton.contentMode = .scaleAspectFit
// I threw this in for S's & G's to see if it would work...it didn't
myButton.translatesAutoresizingMaskIntoConstraints = false
myButton.imageView?.translatesAutoresizingMaskIntoConstraints = true
我不確定我錯過了什么,但我確信這對我來說會是一件令人吃驚的蠢事。 我歡迎關於如何讓UIButton
的背景圖像的contentMode
得到尊重的建議。 感謝您的閱讀。
更新
該按鈕被鍵入為自定義按鈕,而不是系統按鈕。
問題是您使用setBackgroundImage()
方法添加圖像。 這會將您的圖像添加到一些您無法直接訪問的私有UIImageView
,例如myButton.imageView!
. 在您的代碼中,您為按鈕應用contentType
而不是其背景圖像。
如果你想達到這個背景UIImageView
你需要使用subviews
數組。 但是,如果您嘗試在viewDidLoad()
方法中執行此操作,您會發現背景UIImageView
尚未添加,因為您的按鈕layout
方法未被調用。 有 2 種方法可以解決這個問題。
解決方案 1 – 顯式調用layoutIfNeeded
:
override func viewDidLoad() {
super.viewDidLoad()
myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
myButton.layoutIfNeeded()
myButton.subviews.first?.contentMode = .scaleAspectFit
}
解決方案 2 – 在viewDidAppear
方法中移動contentMode
設置。
override func viewDidLoad() {
super.viewDidLoad()
myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
myButton.setTitle("Some title", for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
myButton.subviews.first?.contentMode = .scaleAspectFit
}
希望對你有幫助。
為了簡化接受的答案,您需要做的就是布局子視圖,並且您的設置代碼可以在一個地方完成。
override func viewDidLoad() {
super.viewDidLoad()
myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)
myButton.layoutIfNeeded()
myButton.subviews.first?.contentMode = .scaleAspectFill
}
按鈕的 imageView 屬性和 backgroundImage 屬性是兩個獨立的東西。
與接受的答案不同,您可以改用 imageView 屬性。
override func viewDidLoad() {
super.viewDidLoad()
myButton.setImage(UIImage(named: "myImage.png"), for: .normal)
myButton.imageView?.contentMode = .scaleAspectFill
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.