[英]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.