In following code popover on iPad is not centred for second alert (cities) when iPad is rotated. It works fine for first alert (countries) though. I've printed the values and it's same for both alerts. It seems that despite having correct value for coordinates it doesn't present it in centre on device rotation for second alert.
Why it doesn't show in centre for second alert? How to fix it?
class MyVC: UIViewController {
var popoverController:UIPopoverPresentationController?
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.tableView.reloadData()
if self.popoverController != nil {
popoverController?.sourceView = self.view
print("viewWillTransition():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController?.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController?.permittedArrowDirections = []
}
}
#IBAction func countryButtonClicked(_ sender: UIBarButtonItem) {
displayCountries()
}
func displayCountries() {
let alert = UIAlertController(title: "", message: "", preferredStyle: .actionSheet)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let titleAttributedText = NSMutableAttributedString(
string: "Select Country",
attributes: [
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
)
alert.setValue(titleAttributedText, forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: countryHandler))
for list in Countries {
alert.addAction(UIAlertAction(title: list, style: .default, handler: countryHandler))
}
// For iPad
if let poController = alert.popoverPresentationController {
popoverController = poController
popoverController?.sourceView = self.view
print("displayCountries():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController?.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController?.permittedArrowDirections = []
}
alert.view.addSubview(UIView())
present(alert, animated: false, completion: nil)
}
#IBAction func cityButtonClicked(_ sender: Any) {
showCities()
}
func showCities(){
let alert = UIAlertController(title: "Select City", message: nil, preferredStyle: .actionSheet)
for listItem in Cities {
alert.addAction(UIAlertAction(title: listItem.title, style: .default, handler: cityHandler))
}
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: cityHandler))
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = self.view
print("showCities():width: x: \(UIScreen.main.bounds.size.width*0.5), y: \(UIScreen.main.bounds.size.height*0.5)")
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.size.width*0.5, y: UIScreen.main.bounds.size.height*0.5, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
alert.view.addSubview(UIView())
present(alert, animated: false, completion: nil)
}
}
popoverController must be also assigned in second alert:
if let popoverController = alert.popoverPresentationController {
self.popoverController = popoverController
...
I have this code:
func alertBox(txt: String){
let ac = UIAlertController(title: "MyTtle" , message: "More information in my website: ", preferredStyle: .alert)
let ramkaNaObrazek = CGRect(origin: CGPoint(x: 10, y: 10), size: CGSize(width: 30, height: 30))
let ikonaAlertu = UIImageView(frame: ramkaNaObrazek)
ikonaAlertu.image = UIImage(named: "modal_podpowiedz")
ac.view.addSubview(ikonaAlertu)
ac.addAction(UIAlertAction(title: "Ok" , style: .cancel, handler: { (action: UIAlertAction!) in
}))
present(ac, animated: true)
}
I would like to add after this text: "More information in my website:" + www - a link to my website (http://www.myname.pl).
How can I do this?
You can't add custom fields like text views with clickable links to a UIAlertController. You will need to either create your own modal view controller that acts like a UIAlertController or use a third party framework that does it for you.
I tried to add UILabel into AlertController but it couldnt display on Alert.
I can make it for UIImageView but I couldnt it for UILabel. This followings are my code snippet
let alert = UIAlertController(title: meta.name!, message: "", preferredStyle: .alert)
alert.addAction( UIAlertAction(title: "OK", style: .default, handler: nil) )
var sizeLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 50, height: 50))
sizeLabel.numberOfLines = 0
sizeLabel.lineBreakMode = .byWordWrapping
sizeLabel.sizeToFit()
sizeLabel.preferredMaxLayoutWidth = alert.view.frame.size.width
sizeLabel.font = UIFont(name: "Avenir-Light", size: 20)
sizeLabel.text = "Hello IOS"
alert.view.addSubview(sizeLabel)
So after some quick research it looks like you can't directly add a label to a UIAlertController. You can, however, use AttributedStrings. I used the answer from https://stackoverflow.com/a/30661824/8722754 for my inspiration and updated it to Swift 3:
let attributedString = NSAttributedString(string: "My Message",
attributes: [NSAttributedStringKey.font : UIFont(name: "Avenir-Light", size: 20)!])
let alert = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
alert.setValue(attributedString, forKey: "attributedMessage")
let cancelAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
I am very new to swift coding so I want to know that is there any way to show tableview in alertcontroller using swift.
var alrController = UIAlertController(title: "\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let margin:CGFloat = 8.0
let rect = CGRectMake(margin, margin, alrController.view.bounds.size.width - margin * 4.0, 100.0)
var tableView = UITableView(frame: rect)
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.greenColor()
alrController.view.addSubview(tableView)
let somethingAction = UIAlertAction(title: "Something", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in println("something")})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {(alert: UIAlertAction!) in println("cancel")})
alrController.addAction(somethingAction)
alrController.addAction(cancelAction)
self.presentViewController(alrController, animated: true, completion:{})
private var alertController = UIAlertController()
private var tblView = UITableView()
private func setupCitySelectionAlert() {
let alertVC = UIViewController.init()
let rect = CGRect(x: 0.0, y: 0.0, width: 300.0, height: 300.0)
alertVC.preferredContentSize = rect.size
tblView = UITableView(frame: rect)
tblView.delegate = self;
tblView.dataSource = self;
tblView.tableFooterView = UIView(frame: .zero)
tblView.separatorStyle = .singleLine
alertVC.view.addSubview(tblView)
alertVC.view.bringSubviewToFront(tblView)
alertVC.view.isUserInteractionEnabled = true
tblView.isUserInteractionEnabled = true
tblView.allowsSelection = true
self.alertController = UIAlertController(title: "Title", message: nil, preferredStyle: .alert)
alertController.setValue(alertVC, forKey: "contentViewController")
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
I am trying to add a date picker to an alert view. I can add the animation to the screen based on a button click and I see a black box but no date picker.
Here is what I have so far....
- (IBAction)showDatePicker {
CGRect frame = CGRectMake(200, self.view.frame.size.height, self.view.frame.size.width, 0); //CGRectMake(225, 145, 260, 125);
UIPickerView *datePicker = [[UIPickerView alloc] initWithFrame:frame];
UIAlertView *showDateAlert = [[UIAlertView alloc]
initWithTitle:#"Enter the Code Date"
message:#"Sample message"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Update", nil];
[self.view addSubview:datePicker];
[UIView beginAnimations:#"slideIn" context:nil];
[datePicker setCenter:CGPointMake(datePicker.frame.origin.x, self.view.frame.size.height - datePicker.frame.size.height/2)];
[UIView commitAnimations];
}
I found an example that appears to be working BUT I don't see any dialog or buttons in my alert box, just the date picker itself. Am I missing something here?
- (IBAction)showDatePicker {
CGRect frame = CGRectMake(225, self.view.frame.size.height, self.view.frame.size.width, 125);
UIDatePicker *datePicker = [[UIDatePicker alloc] initWithFrame:frame];
datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setDate:[NSDate date]];
UIAlertView *alert;
alert = [[UIAlertView alloc]
initWithTitle:#"Enter the Code Date"
message:#"Sample message"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Update", nil];
alert.delegate = self;
[alert addSubview:datePicker];
[alert show];
}
In Swift:
let myDatePicker: UIDatePicker = UIDatePicker()
// setting properties of the datePicker
myDatePicker.timeZone = NSTimeZone.localTimeZone()
myDatePicker.frame = CGRectMake(0, 15, 270, 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.view.addSubview(myDatePicker)
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion:{})
I agree with the commenters who have been saying this is not the way to accomplish this, for a couple reasons. First, no-one likes having alert-views constantly popping up. Second, and not applicable to your situation, It might eventually cause an app to be rejected. Apple has changed the wording in the UIAlertView class reference referring to its view hierarchy as private; And we all know how apple feels about you mucking about in what they consider private.
From UIAlertView class reference:
The UIAlertView class is intended to be used as-is and does not
support subclassing. The view hierarchy for this class is private and
must not be modified.
But since you say this is a private app, here goes. A UIAlertView is just a UIView subclass. So all of the rules of frames and bounds still apply. Here's a basic sample of how to adjust the frame of the picker and bounds of the alert to squeeze in the date picker.
// Create alert
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"message" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
// Show alert (required for sizes to be available)
[alert show];
// Create date picker (could / should be an ivar)
UIDatePicker *picker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, alert.bounds.size.height, 320, 216)];
// Add picker to alert
[alert addSubview:picker];
// Adjust the alerts bounds
alert.bounds = CGRectMake(0, 0, 320 + 20, alert.bounds.size.height + 216 + 20);
EDIT
As has been noted by both comments and new answers to many of the 'how do I add some view to a UIAlertView' questions, this method no longer works in iOS7 and above. This should really be taken as evidence that this is a fundamentally bad idea.
Also note the usage of setValue:forKey: in the generally circulated "solution" to the "problem" of not being able to modify Apple's private view hierarchy. setValue:forKey: is one of those methods that draws the interest of the private API scanners. Go search for accessoryView in the UIAlertView documentation and headers. It's not in the docs. The only related item in the headers is an ivar named _accessoryView which is marked as #private.
Again for an in-house or private app I suppose it's okay, just okay though.
You're not going to like this answer, but my suggestion is: don't do that! UIAlertView is not intended for you to add your own subviews; examples that you find of people doing that are examples of wrong behavior. Create your own view containing the picker, text, buttons, etc. that you want, and present it somehow. For example you could present it modally via its own view controller, e.g. with presentModalViewController:animated: or presentViewController:animated:completion:. If you're on an iPad, you could use a popover (it can be modal if that's important).
This is what worked for me (using iOS7). Call this before [alertView show]:
[alertView setValue:customContentView forKey:#"accessoryView"];
Example:
UIAlertView *av = [[UIAlertView alloc] initWithTitle:#"TEST" message:#"subview" delegate:nil cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
v.backgroundColor = [UIColor yellowColor];
[av setValue:v forKey:#"accessoryView"];
[av show];
Source: iOS 7 UIDatePicker in UIAlertView customisation
This is working for me in ios7 and above.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Select Date" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"OK", nil];
UIDatePicker *picker = [[UIDatePicker alloc] initWithFrame:CGRectMake(10, alert.bounds.size.height, 320, 216)];
[alert addSubview:picker];
alert.bounds = CGRectMake(0, 0, 320 + 20, alert.bounds.size.height + 216 + 20);
[alert setValue:picker forKey:#"accessoryView"];
[alert show];
Swift 5 version of #Matheus Domingos answer
let myDatePicker: UIDatePicker = UIDatePicker()
myDatePicker.timeZone = NSTimeZone.local
myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
alertController.view.addSubview(myDatePicker)
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion:{})
Swift 5.2
let myDatePicker: UIDatePicker = UIDatePicker()
myDatePicker.timeZone = NSTimeZone.local
myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
alertController.view.addSubview(myDatePicker)
let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
alertController.addAction(somethingAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: {})
Heres my UIViewController Extension Solution.
typealias DatePickerHandler = (_ success: Bool, _ date:Date) -> Void
typealias TimePickerHandler = (_ success: Bool, _ date:Date) -> Void
extension UIViewController{
func showDatePicker(completionHandler: #escaping DatePickerHandler){
let vc = UIViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let pickerView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: vc.view.bounds.width, height: 300))
pickerView.datePickerMode = UIDatePicker.Mode.date
if #available(iOS 13.4, *) {
pickerView.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
vc.view.addSubview(pickerView)
NSLayoutConstraint.activate([
pickerView.leadingAnchor.constraint(equalTo: vc.view.leadingAnchor,constant: 8),
pickerView.trailingAnchor.constraint(equalTo: vc.view.trailingAnchor,constant: 8),
pickerView.topAnchor.constraint(equalTo: vc.view.topAnchor,constant: 8),
pickerView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor,constant: 8),
])
let editRadiusAlert = UIAlertController(title: "Select Date", message: "", preferredStyle: UIAlertController.Style.actionSheet)
editRadiusAlert.setValue(vc, forKey: "contentViewController")
editRadiusAlert.addAction(UIAlertAction(title: "Select", style: .default, handler: {action in
completionHandler(true,pickerView.date)
}))
editRadiusAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {action in
completionHandler(false,Date())
}))
self.present(editRadiusAlert, animated: true)
}
func showTimePicker(completionHandler: #escaping TimePickerHandler){
let vc = UIViewController()
vc.preferredContentSize = CGSize(width: 250,height: 300)
let pickerView = UIDatePicker(frame: CGRect(x: 0, y: 0, width: vc.view.bounds.width, height: 300))
pickerView.datePickerMode = UIDatePicker.Mode.time
if #available(iOS 13.4, *) {
pickerView.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
vc.view.addSubview(pickerView)
NSLayoutConstraint.activate([
pickerView.leadingAnchor.constraint(equalTo: vc.view.leadingAnchor,constant: 8),
pickerView.trailingAnchor.constraint(equalTo: vc.view.trailingAnchor,constant: 8),
pickerView.topAnchor.constraint(equalTo: vc.view.topAnchor,constant: 8),
pickerView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor,constant: 8),
])
let editRadiusAlert = UIAlertController(title: "Select Time", message: "", preferredStyle: UIAlertController.Style.actionSheet)
editRadiusAlert.setValue(vc, forKey: "contentViewController")
editRadiusAlert.addAction(UIAlertAction(title: "Select", style: .default, handler: {action in
completionHandler(true,pickerView.date)
}))
editRadiusAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {action in
completionHandler(false,Date())
}))
self.present(editRadiusAlert, animated: true)
}
}
Here how to used it in UIViewController
showDatePicker { (isSuccess, date) in
if(isSuccess){
}
}
Happy Coding!