2017-03-10 96 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

相关问题