Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 使用swift 3中的约束使UIButton图像右对齐_Ios_Swift3 - Fatal编程技术网

Ios 使用swift 3中的约束使UIButton图像右对齐

Ios 使用swift 3中的约束使UIButton图像右对齐,ios,swift3,Ios,Swift3,我正在尝试使用约束将图像设置为右侧。我使用这段代码来实现这一点: class func SetImageToRight(button: UIButton) { button.imageView?.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -8.0).isActive = true button.imageView?.centerYAnchor.constraint(e

我正在尝试使用约束将图像设置为右侧。我使用这段代码来实现这一点:

  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中的图像位于按钮的最右侧,无论按钮大小或是否包含文本。

您的问题是按钮具有固有大小,因此根据其大小,将显示尾随的附加图像视图,因此当按钮为空时,大小为零,它通过按钮-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

严格来说,这不是一个干净的答案,但有时用UIView设计一个按钮,并在
0,0,0,0
处覆盖一个带有约束的清晰按钮也会更好。谢谢你的快速回答,但我已经尝试过了,但它不起作用。我没有设置按钮宽度,我已经给出了约束,所以它会自动调整。是的,但是imageView附加到它,所以当它为空时,它会向左移动,所以用黑色边框将imageView挂到该视图上,或者给按钮一个宽度,这样它的空imageView就稳定了确切地说,有没有办法使该图像视图右对齐?