【发布时间】:2021-05-10 19:03:22
【问题描述】:
我一直在尝试获取放置在 UIButton 内的系统图像以缩放比例,但我在网上找到的解决方案似乎都没有。这是我迄今为止尝试过的:
//the cells objects
var acceptButton = UIButton(type: .custom)
var declineButton = UIButton(type: .custom)
override init(frame: CGRect) {
super.init(frame: frame)
//add the contents and set its autolayout constraints
setAutoLayoutConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//function to set the autolayout constraints for the cell's contents
func setAutoLayoutConstraints() {
//create the stack view which will contain the accept and reject buttons
let buttonStackView = UIStackView()
buttonStackView.axis = .horizontal
buttonStackView.distribution = .fillEqually
buttonStackView.alignment = .fill
//add the buttons to the stack view
buttonStackView.addArrangedSubview(acceptButton)
buttonStackView.addArrangedSubview(declineButton)
//add the button stack view to the cell
self.addSubview(buttonStackView)
buttonStackView.translatesAutoresizingMaskIntoConstraints = false
buttonStackView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
buttonStackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
buttonStackView.leadingAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
buttonStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
//add the button images
let addImage = UIImage(systemName: "checkmark.circle")
acceptButton.imageView?.contentMode = .scaleAspectFit
acceptButton.setImage(addImage, for: .normal)
acceptButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
acceptButton.addTarget(self, action: #selector(addButtonClicked), for: .touchUpInside)
let declineImage = UIImage(systemName: "xmark.octagon")
declineButton.imageView?.contentMode = .scaleAspectFit
declineButton.setImage(declineImage, for: .normal)
declineButton.addTarget(self, action: #selector(declineButtonClicked), for: .touchUpInside)
}
(“test test”标签是我为左半部分单元格内容添加的,可以忽略)
我尝试了多种解决方案,例如设置边缘插图、设置按钮的内容模式和按钮的图像视图、使用自定义按钮等,但我似乎无法调整图像大小。
注意:当我使用 setBackgroundImage 将图像设置为背景图像时,我可以调整按钮的大小,但无法缩放适合它的纵横比,只能水平和垂直填充它,这不是我想要做的。
感谢任何帮助,谢谢!
【问题讨论】: