2014-12-26 31 views
8
var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton 
var image = UIImage(named: "myimage.png") as UIImage! 
button.frame = CGRectMake(0, 0, 100, 100) 
button.setImage(image, forState: .Normal) 

Ho un'immagine che ho impostato sul mio pulsante, ma mi piacerebbe ridimensionarla per essere più piccola del pulsante (ad esempio l'immagine dovrebbe essere 50,50) e al centro nel pulsante. Come potrei farlo in Swift?Come ridimensionare l'immagine e centrarla su un UIButton in Swift?

risposta

17

Xcode 8.3.1 • Swift 3,1

let customButton = UIButton(type: .custom) 
let image = UIImage(named: "myimage.png") 

func buttonTouchDown(_ button: UIButton) { 
    print("button Touch Down") 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
    button.frame = CGRect(x: 0, y: 0 , width: 100, height: 100) 
    button.backgroundColor = .clear 
    button.addTarget(self, action: #selector(buttonTouchDown), for: .touchDown) 
    button.setTitle("Title", for: .normal) 
    button.setTitleColor(.black, for: .normal) 
    button.setImage(image, for: .normal) 
    button.imageEdgeInsets = UIEdgeInsetsMake(25,25,25,25) 
    view.addSubview(button) 
} 
6

O tramite XIB dopo aver selezionato il vostro UIButton.

Assicurati che i tuoi riquadri siano tutti uguali.


enter image description here

5

che ci sia un modo molto più semplice per fare questo in cui non si ha a che fare con inserti di contenuti. Qui la sua è:

var button = UIButton.buttonWithType(UIButtonType.Custom) as UIButton 
var image = UIImage(named: "myimage.png") as UIImage! 
button.frame = CGRectMake(0, 0, 100, 100) 
button.setImage(image, forState: .Normal) 
button.contentMode = .center 
button.imageView?.contentMode = .scaleAspectFit 
0

Se avete questo problema e il pulsante è all'interno di uno stackView

Selezionare il pulsante e aggiungere vincolo: Aspect Ratio

Dovrebbe (a seconda della configurazione stackView) mantenere l'aspetto.

Spero che aiuti.

1

Swift 4, Swift 3

var image = UIImage(named: "myimage.png") as UIImage! 
btnetc.setImage(image, for: .normal) 
btnetc.imageView?.contentMode = .scaleAspectFill 

o

btnetc.imageView?.contentMode = .scaleAspectFit 

o

btnetc.imageView?.contentMode = .scaleToFill 
Problemi correlati