2017-04-07 205 views
-1

我添加背景圖片到swift中的按鈕。實際圖像尺寸爲100x100。這個想法是,當我點擊圖像時,會出現更改配置文件圖像的彈出窗口。然後,您可以從圖庫中選擇照片並保存。
保存照片後,圖像顯示完整。但是,問題是在我從圖庫中選擇照片之前,我設置了默認圖像。請參閱以下截圖。
按鈕背景圖片在swift 3中

enter image description here

資料女性形象應該是大的背景綠色。這是我的代碼。

let img = UIImage(data: match.value(forKey: "imageData") as! Data) 
btnProfile.frame = CGRect(x: 10, y: 100, width: 100, height: 100) 
btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill 
btnProfile.setImage(img, for: UIControlState.normal) 

if(user_gender == "Female"){ 

     btnProfile.setImage(UIImage(named: "femaleprofile_image")?.withRenderingMode(.alwaysOriginal), for: .normal) 
     btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill 
} 

影像尺寸爲1 @ - > 40×40像素和2 @ - > 80×80像素。
請大家幫助我如何解決這個問題。

+0

[如何調整一個UIButton的ImageView的?(HTTP的可能重複:// stackoverflow.com/questions/1957317/how-do-i-scale-a-uibuttons-imageview) –

回答

1

你不應該在這裏設置你的默認圖像。你應該已經有,因爲你開照相館所有你需要做的就是添加的協議功能imagePickerController didFinishPickingMediaWithInfo的UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 
    // if user has selected an image from gallery use that 
    if let profileImage = info[UIImagePickerControllerEditedImage] as UIImage { 
      // use the selected image from gallery here 
      btnProfile.setImage(profileImage, for: .normal) 
     } else { 
      // else use your logic 
      let img = UIImage(data: match.value(forKey: "imageData") as! Data) 
       btnProfile.frame = CGRect(x: 10, y: 100, width: 100, height: 100) 
       btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill 
       btnProfile.setImage(img, for: UIControlState.normal) 

      if(user_gender == "Female"){ 
       btnProfile.setImage(UIImage(named:"femaleprofile_image")?.withRenderingMode(.alwaysOriginal), for: .normal) 
       btnProfile.imageView?.contentMode = UIViewContentMode.scaleToFill 
      } 

    } 
} 
+0

Bro @ khalidAfridi,請讓我解釋一下我的應用如何工作。當您第一次運行該應用時,該應用會詢問您的性別狀態。如果你點擊女性形象,那麼女性形象將顯示在其中。像上面的截圖一樣。然後,如果您想添加圖片,只需點擊女性圖片並從您的圖庫中選擇照片。這是我的應用程序的工作原理。 –

+0

@MayPhyu我認爲我的答案仍然有效。也許我不太明白,或者你不能清楚地解釋你的問題,如果用戶選擇了一張照片,那麼你應該改變按鈕圖像,否則它不應該。 –

+0

兄弟我現在可以解決它。這是我添加的代碼。 btnProfile.contentHorizo​​ntalAlignment = .fill btnProfile.contentVerticalAlignment = .fill –