I have a minor issue, which I am probably not able to get my head around. I have a uibutton added programmatically. To that button I am adding a UIImage. I am just adding basic constraints, but for some reason it tends to shrink to a smaller size while running on screen.
Following is the code I have for generating the button:
var shareButton: UIButton!
func addShareButton() {
shareButton = UIButton()
shareButton.autoresizesSubviews = false
shareButton.clipsToBounds = true
shareButton.translatesAutoresizingMaskIntoConstraints = false
shareButton.adjustsImageWhenHighlighted = false
shareButton.setImage(UIImage(named: "wshare"), for: .normal)
shareButton.addTarget(self, action: #selector(shareButtonPressed), for: .touchDown)
shareButton.addTarget(self, action: #selector(shareButtonReleased), for: .touchUpInside)
view.addSubview(shareButton)
}
func addConstraints() {
NSLayoutConstraint.activate([
// Share Button
shareButton.widthAnchor.constraint(equalToConstant: 60),
shareButton.heightAnchor.constraint(equalToConstant: 60),
shareButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -15),
shareButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -25),
])
}
override func updateViewConstraints() {
addConstraints()
super.updateViewConstraints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
addShareButton()
}
And what it generates is this:
The bigger box is supposed to be the actual size which is 60x60, but it magically shrinks to 32x32.
Can you help me point the issue. I know I am missing something quite silly, But I am not able get my head around it.
Personally, I like to keep my objects separate. While UIButton
has a setImage(:UIImage)
method, I prefer to create a UIButton
then add my own UIImageView
to it then add my own UIImage
. So, in hierachy
-- UIButton
-- UIImageView
-- UIImage
With this, you can specify the specific bounds and any other variables associated to UIImageView
. I find this methodology to be incredibly more concrete, especially if you have to alter the UIImageView
.