我一直在寻找几个小时,但我发现的只是旧答案,说它无法完成。
我有一个按钮,我希望背景图像尽可能大,同时保持其纵横比。无论我做什么,背景图像都会不断拉伸(stretch)。我试过了。
var bluecircle = #imageLiteral(resourceName: "BLUE.png")
monBreak.contentMode = UIViewContentMode.scaleAspectFit
monBreak.setBackgroundImage(bluecircle, for: UIControlState.normal)
我真的需要制作一个 ImageView 并在其上放置一个不可见的按钮吗?这似乎欢迎许多可能出错的新事物。
我试过了
@IBOutlet weak var monBreak: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var bluecircle = #imageLiteral(resourceName: "BLUE.png")
let theimagebehindmonBreak = UIImageView(image: bluecircle)
theimagebehindmonBreak.frame = CGRectFromString( "{{0,0},{40,40}}")
monBreak.contentMode = UIViewContentMode.scaleAspectFit
monBreak.addSubview(theimagebehindmonBreak)
theimagebehindmonBreak.image=bluecircle
theimagebehindmonBreak.contentMode = UIViewContentMode.scaleAspectFit
这使宽高比正确,但由于我希望布局是动态的,将其大小设置为固定值将不起作用,而且它没有居中。
起初我厌倦了像这样简单地应用按钮的约束
var dacontraints = NSLayoutConstraint(monBreak.constraints)
但此时我收到错误消息“无法使用类型为‘{[NSLayoutconstraints]}”的参数列表调用类型为‘NSLayoutConstraint’的初始化程序
这让我很痛苦
最佳答案
听起来像是适合子类化的解决方案。
子类 UIButton,在 init 中添加一个 ImageView,将其调整到 frame,并正确设置 contentMode。
关于ios - 保持 UIbuttons 背景图片的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40529717/