【问题标题】:IOS 15 UIButton right alignment not workingIOS 15 UIButton右对齐不起作用
【发布时间】:2022-07-22 17:12:22
【问题描述】:

在 IOS 15 中,即使将按钮文本对齐设置为右对齐,按钮标题文本后也会留下很少的空间。 如下图所示,它在单词 Test 之后留下空格。 我怎样才能删除这个空间?我希望文本中的字母“t”触摸按钮的尾部。

在 ios 14 及以下版本中看起来像这样

【问题讨论】:

  • 尝试设置样式默认并输入自定义

标签: ios swift objective-c uibutton ios15


【解决方案1】:

您可以尝试将其与 DispatchQueue

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

【讨论】:

  • 它不工作。仍然可以看到按钮文字后的空格
【解决方案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

这是结果:

【讨论】:

    【解决方案3】:

    尝试同时设置:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-30
      • 2018-11-11
      • 1970-01-01
      • 2018-06-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      相关资源
      最近更新 更多