我在iOS 15中遇到了一个问题,当设置图像到右角不工作,而在iOS 15之前,它是正常工作。
我想实现的目标:
我的成就:
下面是我在iOS 15中使用的完整代码:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let btnDropdown = getDropdownButton()
btnDropdown.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(btnDropdown)
NSLayoutConstraint.activate([
btnDropdown.heightAnchor.constraint(equalToConstant: 44),
btnDropdown.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
btnDropdown.trailingAnchor.constraint(equalTo: view.layoutMarginsGuide.trailingAnchor),
btnDropdown.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 30)
])
}
fileprivate func getDropdownButton() -> UIButton {
var button: UIButton!
if #available(iOS 15.0, *),
let btnConfig = getButtonConfiguration() {
button = UIButton(configuration: btnConfig)
} else {
button = UIButton(type: .custom)
}
button.setTitle("Select Tags", for: .normal)
setupGeneralSettings(for: button)
return button
}
fileprivate func setupGeneralSettings(for button: UIButton) {
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
button.contentHorizontalAlignment = .left
button.layer.borderWidth = 1
button.layer.cornerRadius = 8
button.clipsToBounds = true
button.backgroundColor = .lightGray.withAlphaComponent(0.3)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
button.setTitleColor(UIColor.black, for: .normal)
}
@available(iOS 15.0, *)
fileprivate func getButtonConfiguration() -> UIButton.Configuration? {
var btnConfig = UIButton.Configuration.plain()
btnConfig.buttonSize = .medium
btnConfig.titleAlignment = .leading
btnConfig.imagePlacement = .trailing
btnConfig.image = UIImage(systemName: "arrowtriangle.down.circle")
btnConfig.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)
btnConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 14, weight: .medium)
return outgoing
}
return btnConfig
}
}
**注意:**当我说iOS 15时,我的意思是我正在使用UIButton.配置,因为UIButton的titleEdgeInset、imageEdgeInset和contentEdgeInset在iOS 15中已被弃用。此外,我认为UIButton.配置中缺少了一些东西,通过该配置,图像将到达按钮的右边缘,但我不确定是什么。
如果您还需要其他信息,请告诉我。
提前致谢!
2条答案
按热度按时间k2arahey1#
您 * 可能 * 会遇到一些问题,通过混合 * 一些 * 旧风格的按钮代码与新的
.configuration
风格,但是...在
setupGeneralSettings()
中更改此行:更改为:
并查看是否得到了所需的布局。
dfuffjeb2#
您可以像这样添加外部图像:
在控制器类下,声明对象:
在viewDidLoad中(或在函数中)设置对象的属性和约束:
这就是结果: