0

I'm trying to create a button for adding an image which has a small camera icon next to the text "add image".

I have managed to get this result with the following code: enter image description here

let btn = UIButton(type: .system)
let img = UIImage(named: "camera")
    
btn.setImage(img, for: .normal)
btn.contentMode = .scaleAspectFit
btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
btn.imageEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)
    
stackView.addArrangedSubview(btn)
let btnHeight = NSLayoutConstraint(item: btn, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 40)
NSLayoutConstraint.activate([btnHeight])

The problem is that the aspect ratio is not correct even though contentMode is set to .scaleAspectFit. If I increase the left and right values for the imageEdgeInsets nothing changes.

Does anyone know what I'm missing?

Community
  • 1
  • 1
Developer
  • 736
  • 7
  • 30
  • you need to take button height and width according to image or just create image according to button height and width which you want to set. (Or you can add ImageView on button.) – PiyushRathi Dec 12 '16 at 13:24
  • @Piyush, thanks for the answer. I'm not sure what you mean? Can you give me an example? – Developer Dec 12 '16 at 13:28
  • Suppose you need a button 240x40 so create image which will look cool in 240x40 button size. just create it as 240x40 or 480x80 for @2x – PiyushRathi Dec 12 '16 at 13:31

0 Answers0