在产生意外结果的按钮中居中放置图像
问题描述:
我试图在UIButton
中居中放置一个图像,并产生意外的结果。 (1)当我在控制台中打印按钮和图像的中心点时,它们不匹配,但它们应该,不应该吗? (2)当我将.center
更改为其他任何内容时,如.left
,图像仍保留在中心位置。 .center
似乎没有效果。
在产生意外结果的按钮中居中放置图像
func addSearchButton() {
let button = UIButton()
button.frame.size.width = 56
button.frame.size.height = 56
button.frame.origin.y = 20 + 8
button.frame.origin.x = 8
button.imageView?.contentMode = .center
button.backgroundColor = UIColor.green
button.setImage(#imageLiteral(resourceName: "searchIcon"), for: .normal)
button.setImage(#imageLiteral(resourceName: "searchIcon"), for: .highlighted)
button.addTarget(self, action: #selector(openSearch), for: .touchUpInside)
view.addSubview(button)
print("search: \(button.center.x)")
print("search: \(button.imageView!.center.x)")
}
我在做什么错在这里?
答
(1)当然,他们不匹配,因为他们有不同的超级视图。 (查看按钮)??
(2)看起来像你期待布局对齐。 UIImageView的contentMode通常具有不同的效果,具体取决于其帧大小和图像大小。如果您想更改图像位置,请改为更新imageEdgeInsets。
公平点(1)LOL。所以我在这个例子中使用'button.imageView?.contentMode = .center'是不正确的?将图像定位到按钮内部左侧或右侧的唯一方法是使用插页手动进行定位? – sconewolf