IOS 15 UIButton 右对齐不起作用

IOS 15 UIButton right alignment not working

提问人:AVR 提问时间:4/11/2022 更新时间:7/22/2022 访问量:2862

问:

在 IOS 15 中,即使将按钮文本向右对齐后,它也会在按钮标题文本后留下很少的空间。 如下图所示,它保留了单词 Test 后面的空格。 如何删除此空间?我希望文本中的字母“t”触摸按钮的尾部。

enter image description here

在 ios 14 及更低版本中,它看起来像这样

enter image description here

iOS 版 Swift Objective-C UIBUTTON iOS15

评论

2赞 Raja Kishan 4/11/2022
尝试设置样式默认值并键入自定义

答:

-3赞 Hiren Bharodiya 4/11/2022 #1

您可以尝试将其与 DispatchQueue 一起使用

button.contentHorizontalAlignment = .left
emailBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)

评论

0赞 AVR 4/11/2022
它不起作用。仍能看到按钮文本后面的空格
2赞 Fabio 4/12/2022 #2

这是一个小技巧,或者你可以用UIButton.Configuration来做到这一点,像这样设置你的按钮:

let myButton: UIButton = {
    let b = UIButton()
    b.backgroundColor = .white
    b.tintColor = .black
    b.layer.cornerRadius = 8
    b.clipsToBounds = true
    b.setTitle(" My button Test", for: .normal) // space in front of string = space fron text and image
    b.setTitleColor(.black, for: .normal)
    b.titleLabel?.font = .systemFont(ofSize: 17, weight: .regular)
    b.contentHorizontalAlignment = .right
    b.setImage(UIImage(systemName: "bag"), for: .normal)
    b.configuration?.imagePlacement = .leading // use button configuration to add image position
    b.translatesAutoresizingMaskIntoConstraints = false

    return b
}()

这是 UIButton.Configuration 样式:

let myButton: UIButton = {
    
    var filled = UIButton.Configuration.filled()
    filled.title = "My button Test"
    filled.buttonSize = .large
    filled.baseBackgroundColor = .white
    filled.baseForegroundColor = .black
    filled.cornerStyle = .medium
    filled.image = UIImage(systemName: "bag", withConfiguration: UIImage.SymbolConfiguration(scale: .large))
    filled.imagePlacement = .leading
    filled.imagePadding = 4
    filled.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

    let b = UIButton(configuration: filled, primaryAction: nil)
    b.contentHorizontalAlignment = .right
    b.translatesAutoresizingMaskIntoConstraints = false

    return b
}()

在 viewDidLoad 中显示按钮并设置约束:

view.addSubview(myButton)
myButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
myButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
myButton.widthAnchor.constraint(equalToConstant: 200).isActive = true

结果如下:

enter image description here

-3赞 lecuong 7/22/2022 #3

尝试同时设置:

button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 25, bottom: 0, right: 00)
button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 00)