sconewolf sconewolf - 27 days ago 8
Swift Question

Centering image in button producing unexpected results

I'm trying to center an image inside a

UIButton
and it's producing unexpected results.

(1) When I print the center points of the button and the image in the console, they don't match up, but they should, shouldn't they?

(2) When I change
.center
to anything else, like
.left
, the image still remains in the center.
.center
appears to have no effect.




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)")

}


What am I doing wrong here?

Answer Source

(1) Of course, they don't match up because they have different superviews. (view vs button)??

(2) Seems like you are expecting layout alignment. UIImageView's contentMode usually has different effects depending on its frame size and image size. If you want change the image position, update imageEdgeInsets instead.