【问题标题】:Make UIButton Image right aligned using constraint in swift 3在swift 3中使用约束使UIButton Image右对齐
【发布时间】:2018-01-22 13:49:07
【问题描述】:

我正在尝试使用约束将图像设置为右侧。我正在使用此代码来实现此目的:

  class func SetImageToRight(button: UIButton) {
        button.imageView?.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -8.0).isActive = true
        button.imageView?.centerYAnchor.constraint(equalTo: button.centerYAnchor, constant: 0.0).isActive = true
        button.imageView?.widthAnchor.constraint(equalToConstant: button.imageView!.frame.width).isActive = true

        button.imageView?.translatesAutoresizingMaskIntoConstraints = false
    }

但问题是当 UIButton 图像内有任何文本时右对齐但如果按钮文本为空图像左对齐。

没有任何文字的按钮:

带文字的按钮:

我希望 UIButton 内的图像位于按钮的最右侧,无论按钮的大小是多少或是否有文本。

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

    您的问题是按钮具有固有大小,因此根据它的大小,将显示尾随附加的 imageView,因此当它为空时,大小为零,它通过 button - 8 的尾随向左移动的图像,当它不为空时向右移动,因此您可以为包含它的视图和 imageView 中的按钮设置静态宽度

     button.widthAnchor.constraint(equalTo: button.superview?.widthAnchor, multiplier: 0.8, constant: 0)
    

    或者将按钮的 imageView 挂钩到按钮的 superview 尾部

    button.imageView?.trailingAnchor.constraint(equalTo: button.superView.trailingAnchor, constant: -8.0).isActive = true
    

    【讨论】:

    • 感谢您的快速回答,但我已经尝试过了,但它不起作用。
    • 我没有设置按钮宽度,我已经给出了约束,所以它会自动调整。
    • 是的,但是 imageView 附加在它上面,所以当它为空时它会向左移动
    • 所以将 imageView 钩到带有黑色边框的那个视图上,或者给按钮一个宽度,这样它就是空的 imageView 是稳定的
    • 没错,有什么办法可以让图像视图右对齐?
    【解决方案2】:

    严格来说不是一个干净的答案,但有时也更好地设计一个带有 UIView 的按钮并在0, 0, 0, 0 处覆盖一个带有约束的清晰按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2020-08-30
      • 2015-08-30
      • 1970-01-01
      • 2021-04-29
      相关资源
      最近更新 更多