2017-03-10 128 views
0

我想在UIAlertbox中添加圖像,以便添加以下代碼。
如何在Swift 3中將圖像添加到UIAlertbox中?

enter image description here

let alertController = UIAlertController(title: "Gender", message: "" , preferredStyle: .alert) 

    // Create the actions 
     let okAction = UIAlertAction(title: "Female", style: UIAlertActionStyle.default) { 
      UIAlertAction in 
       // exit(0) 
       debugPrint("Press OK") 

     } 
     let cancelAction = UIAlertAction(title: "Male", style: UIAlertActionStyle.cancel) { 
       UIAlertAction in 

     } 


// Add the actions 
    okAction.setValue(#imageLiteral(resourceName: "female_image"), forKey: "image") 
    cancelAction.setValue(#imageLiteral(resourceName: "male_image"), forKey: "image") 
    alertController.addAction(okAction) 
    alertController.addAction(cancelAction) 

當我運行應用程序,只有一個形象出現。這有什麼問題?
請大家幫幫我嗎?

回答

3

試試這個代碼其工作在swift3

let alertMessage = UIAlertController(title: "Gender", message: "", preferredStyle: .alert) 

    let image = UIImage(named: "blanckstar") 
    let action = UIAlertAction(title: "Male", style: .default) 
    { 
     UIAlertAction in 
     // exit(0) 
     debugPrint("Press Male") 

    } 
    action.setValue(image, forKey: "image") 

    let image2 = UIImage(named: "blanckstar") 
    let action2 = UIAlertAction(title: "Female", style: .default) 
    { 
     UIAlertAction in 
     // exit(0) 
     debugPrint("Press Female") 

    } 

    action2.setValue(image2, forKey: "image") 

    alertMessage.addAction(action) 
    alertMessage.addAction(action2) 

    self.present(alertMessage, animated: true, completion: nil) 

快樂Coading :-)

改變圖像大小,你可以用fontAwesome嘗試只安裝莢

pod'FontAwesome.swift'並導入FontAwesome_swift

這裏是代碼.....

let alertMessage = UIAlertController(title: "Gender", message: "", preferredStyle: .alert) 

    let image = UIImage.fontAwesomeIcon(name: .male, textColor: UIColor.black, size: CGSize(width: 50, height: 50)) 
    let action = UIAlertAction(title: "Male", style: .default) 
    { 
     UIAlertAction in 
     // exit(0) 
     debugPrint("Press Male") 

    } 
    action.setValue(image, forKey: "image") 

    let image2 = UIImage.fontAwesomeIcon(name: .female, textColor: UIColor.black, size: CGSize(width: 50, height: 50)) 
    let action2 = UIAlertAction(title: "Female", style: .default) 
    { 
     UIAlertAction in 
     // exit(0) 
     debugPrint("Press Female") 

    } 

    action2.setValue(image2, forKey: "image") 

    alertMessage.addAction(action) 
    alertMessage.addAction(action2) 

    self.present(alertMessage, animated: true, completion: nil) 
+0

你好兄弟@seggy,你的代碼工作!非常感謝。但是,我想編輯圖像大小。所以,我添加了這些代碼。讓femaleimgView = UIImageView(frame:CGRect(x:10,y:10,width:30,height:30))和femaleimgView.image = femaleimage。 Action1.setValue(femaleimgView,forKey:「image」)。當我添加這些代碼時,我得到了錯誤。 :( –

+0

讓我檢查.... – seggy

+0

是否對你有用? – seggy

相關問題