How Add Image into UIAlertbox in Swift 3?

半城伤御伤魂 提交于 2019-12-02 19:08:37

问题


I would like to add Image in UIAlertbox so I add the following codes.

 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)

When I run the app, only one Image appear. What's wrong with this?
Please anyone help me?


回答1:


Try this code its working in 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)

Happy Coading :-)

for changing size of image you can try with fontAwesome just install pod

pod 'FontAwesome.swift' and import FontAwesome_swift

here is the code.....

    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)


来源:https://stackoverflow.com/questions/42715152/how-add-image-into-uialertbox-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!