Adr*_*ian 6 uibutton ios swift
我把在一个应用程序,我即将出版的收尾,我已经enountered困难得到了contentMode一个中UIButton的背景图片被尊重.无论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
Run Code Online (Sandbox Code Playgroud)
我不确定我缺少什么,但我放心,这对我来说是一件令人吃惊的事.我欢迎我如何能获得更好的建议contentMode一中UIButton的背景图片被尊重.谢谢你的阅读.
更新
该按钮被键入为自定义按钮,而不是系统按钮.
Yur*_*hev 16
问题是您使用setBackgroundImage()方法添加图像.这会将您的图片添加到UIImageView您无法直接访问的私有图片中myButton.imageView!.在您的代码中,您正在申请contentType按钮而不是其背景图片.
如果要达到此背景UIImageView,则需要使用subviews数组.但是如果您尝试在viewDidLoad()方法中执行此操作,您会发现UIImageView尚未添加背景,因为您的按钮layout方法未被调用.因此,您可以在方法中显式调用layoutIfNeeded()或移动contentMode设置viewDidAppear().
希望它能帮到你.
override func viewDidLoad() {
myButton.setBackgroundImage(UIImage(named: "myImage"), for: .normal)
myButton.setTitle("Some title", for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
myButton.subviews.first?.contentMode = .scaleAspectFit
}
Run Code Online (Sandbox Code Playgroud)
为了简化可接受的答案,您要做的就是布置子视图,并且可以在一个地方完成设置代码。
override func viewDidLoad() {
super.viewDidLoad()
myButton.setBackgroundImage(UIImage(named: "myImage.png"), for: .normal)
myButton.layoutIfNeeded()
myButton.subviews.first?.contentMode = .scaleAspectFill
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3683 次 |
| 最近记录: |