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?
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)
Related
I create a simple share button to share some texts. Although the ShareSheet is working, I received unexpected errors messages in my console. I am a beginner level and I have no idea whether should I worry about the error message. Please let me know if there is a better solution for ShareSheet.
The messages are
2021-11-22 19:36:03.677822-0500 ZSV5_IDChange[8282:264096] [LayoutConstraints] Changing the translatesAutoresizingMaskIntoConstraints property of a UICollectionReusableView that is managed by a UICollectionView is not supported, and will result in incorrect self-sizing. View: <_UIActivityContentFooterView: 0x7feec8925ad0; baseClass = UICollectionReusableView; frame = (16 256; 358 52); layer = <CALayer: 0x6000038ec4c0>>
2021-11-22 19:36:03.688591-0500 ZSV5_IDChange[8282:264096] [default] -imageForImageDescriptor: can do IO please adopt -imageForDescriptor: for IO free drawing or -prepareImageForDescriptor: if IO is allowed. (This will become a fault soon.)
2021-11-22 19:36:03.859368-0500 ZSV5_IDChange[8282:264096] [UICollectionViewRecursion] cv == 0x7feec7065a00 Disabling recursion trigger logging
Also, I get UIApplication.shared.windows will deprecate in iOS 15. If it is true, I think it will be a smarter choice to use ShareSheet() instead of using private func shareText(text: String). Please have a look at my code before I overcomplicated my question.
Below is my simple code:
import Foundation
import SwiftUI
struct DataArray: Identifiable {
let id: Int
let cities: String
let name1: String
let name2: String
let isFavorite: Bool
}
public struct ListDataArray {
static let dot = [
DataArray(id: 1,
cities: "Baltimore"
name1: "John",
name2: "Mike",
isFavorite: False),
DataArray(id: 2,
cities: "Frederick"),
name1: "Joe",
name2: "Swift",
isFavorite: False),
DataArray(id: 3,
cities: "Catonsville"
name1: "Susan",
name2: "Oliver",
isFavorite: False),
// There will be a lot of data
]
}
struct TestShareSheet3: View {
var data: DataArray
#State private var showShareSheet: Bool = false
var body: some View {
VStack {
Button {
self.showShareSheet.toggle()
//shareText(text: "\(data.cities)\n\(data.name1) - \(data.name2)")
} label: {
Text("Share")
.foregroundColor(.blue)
.font(.title3)
.padding()
.background(Color.green)
.cornerRadius(10)
}
.sheet(isPresented: self.$showShareSheet) {
// On Dismiss
} content: {
ShareSheet(activityItems: ["\(data.cities)\n\(data.name1) - \(data.name2)"])
}
}
}
// This function also has the same issue
private func shareText(text: String) {
let av = UIActivityViewController(activityItems: [text], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
if UIDevice.current.userInterfaceIdiom == .pad {
av.popoverPresentationController?.sourceView = UIApplication.shared.windows.first
av.popoverPresentationController?.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2.1, y: UIScreen.main.bounds.height / 1.3, width: 200, height: 200)
}
}
}
struct Test2_Previews: PreviewProvider {
static var previews: some View {
// Testing purposes
TestShareSheet3(data: ListDataArray.dot[1])
}
}
struct ShareSheet: UIViewControllerRepresentable {
typealias Callback = (_ activityType: UIActivity.ActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ error: Error?) -> Void
let activityItems: [Any]
let applicationActivities: [UIActivity]? = nil
let excludedActivityTypes: [UIActivity.ActivityType]? = nil
let callback: Callback? = nil
func makeUIViewController(context: Context) -> UIActivityViewController {
let controller = UIActivityViewController(
activityItems: activityItems, applicationActivities: applicationActivities)
controller.excludedActivityTypes = excludedActivityTypes
controller.completionWithItemsHandler = callback
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) { }
}
I have 4 tabs in the tab bar. Currently, I am working in the 4th tab, and having an imagePickerController. After the imagePickerController dismissed, it goes to the default tab (1st tab). How can I make it go to the current (4th) tab?
class EditMyPostViewController: UIViewController {
#IBOutlet weak var postImageView: UIImageView!
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
#IBAction func updatePhotoTapped(_ sender: Any) {
let alert = UIAlertController(title: "Add a picture", message: "How do you want to upload the picture?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { action in
self.takePhotoWithCamera()
}))
alert.addAction(UIAlertAction(title: "Use Existing Photo", style: .default, handler: { action in
self.getPhotoFromLibrary()
}))
self.present(alert, animated: true)
}
}
extension EditMyPostViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func takePhotoWithCamera() {
if (!UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)) {
let alertController = UIAlertController(title: "No Camera", message: "The device has no camera.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
} else {
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
}
func getPhotoFromLibrary() {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
{
postImageView.image = image
}
dismiss(animated: true, completion: nil)
}
}
The imagePicker is present in the 2 functions takePhotoWithCamera() and getPhotoFromLibrary().
In the last function, I tried to dismiss(animated: true, completion: nil), but it goes to the default tab instead of the current tab. How can I present the current ViewController?
I tried
present(self, animated: true, completion: nil)
But it will cause an Exception: Application tried to present modally an active controller
I've created an actionSheet with 3 options that push to other view controllers and call a number. This option is on a button on a navigation bar on each screen of my app. I'm trying to find a way to reuse the code without literally re-typing it for every screen. I understand there is a way to do this through subclassing a UIButton but I've searched for days and can't find a definitive answer on how to actually code the subclass. My code right now is the following:
class moreButton: UIButton {
#IBAction func displayActionSheet(_ sender: Any) {
let alertController = UIAlertController(title: nil, message: "Get Your Roast On", preferredStyle: .actionSheet)
let followAction = UIAlertAction(title: "Follow Us", style: .default, handler: {(action: UIAlertAction!)->Void in self.performSegue(withIdentifier: "moveSegue", sender: self)
})
let shopAction = UIAlertAction(title: "Visit Shop", style: .default, handler: {(action: UIAlertAction!)->Void in self.performSegue(withIdentifier: "shopSegue", sender: self)
})
let callAction = UIAlertAction(title: "Call Us Now", style: .default) { _ in
let url:URL = URL(string: "tel://number")!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(followAction)
alertController.addAction(shopAction)
alertController.addAction(callAction)
alertController.addAction(cancel)
self.present(alertController, animated: true, completion: nil)
}
}
I'm getting the error:
value of type 'moreButton' has no member 'performSegue'
in both the followAction and shopAction lines and "value of type 'moreButton' has no member 'present'" on the last line. This code was working when I had created an IBAction directly from the button but now it seems to have errors that I'm not sure how to correct.
You're getting those errors because performSegue and present are UIViewController methods.
Instead of subclassing UIButton, I'd create a new helper class, with a class method to build the UIAlertController for you. The method would accept a UIViewController as its parameter, so that it can build the UIAlertActions correctly.
You'd call this new method from displayActionSheet like:
let alertController = ActionSheetBuilder.build(viewController: self)
present(alert, animated: true, completion: nil)
Adapting your creation code into the new class would come out something like:
final class ActionSheetBuilder {
class func build(viewController: UIViewController) -> UIAlertController {
let alertController = UIAlertController(title: nil, message: "Get Your Roast On", preferredStyle: .actionSheet)
let followAction = UIAlertAction(title: "Follow Us", style: .default, handler: {(action: UIAlertAction!)->Void in viewController.performSegue(withIdentifier: "moveSegue", sender: viewController) })
let shopAction = UIAlertAction(title: "Visit Shop", style: .default, handler: {(action: UIAlertAction!)->Void in viewController.performSegue(withIdentifier: "shopSegue", sender: viewController) })
let callAction = UIAlertAction(title: "Call Us Now", style: .default) { _ in
let url:URL = URL(string: "tel://2845471035")!
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(followAction)
alertController.addAction(shopAction)
alertController.addAction(callAction)
alertController.addAction(cancel)
return alertController
}
}
I have an UIImagePickerController that works, but I wanted to let the user decide whether he shoots the image or picks it from library. So this is my code trying to do it with alert:
#IBAction func cameraButton(_ sender: UIButton) {
picker.allowsEditing = true
let alert = UIAlertController(title: "Choose one of the following:", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { action in
self.picker.sourceType = .photoLibrary
}))
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
self.picker.sourceType = .camera
}))
self.present(alert, animated: true, completion: nil)
present(picker, animated: true, completion: nil)
}
However, once I click on one of the actions in the alert, nothing happens, it just gets out of the alert but not presenting my picker
Any help is appreciated
I solved it by presenting inside the action like this:
#IBAction func cameraButton(_ sender: UIButton) {
picker.allowsEditing = true
let alert = UIAlertController(title: "Choose one of the following:", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { action in
self.picker.sourceType = .photoLibrary
self.present(self.picker, animated: true, completion: nil)
}))
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { action in
self.picker.sourceType = .camera
self.present(self.picker, animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
Code:
let alertController = UIAlertController(title: "StopRequest", message: msg, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction!) in
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction!) in
}
alertController.addAction(OKAction)
self.present(alertController, animated: true, completion:nil)
I create a UIAlertViewController in swift3.
Alertview is working fine.Please help me on how to handle ok and cancel events.If we have more than one alert how to differentiate them?.thanks in advance
let alert = UIAlertController(title: "Wrong Email Or Password", message: "Please Check Your Email or Password", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default)
{
_ in // add actions here
}
)
self.present(alert, animated: true, completion: nil)