Swift UIAlertController with url in text - ios

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.

Related

Popoverview is not centred on iPad rotation

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
...

How to add UILabel into UIAlertController

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)

How to add a UIStepper to AlertView

I want to add a UIStepper to my alerView but the stepper is not showing here is my code
var alert = UIAlertView(title: "Hello works", message: "\n\n", delegate: nil, cancelButtonTitle: "OK", otherButtonTitles: "")
var stepper = UIStepper()
stepper.frame = CGRect(x: CGFloat(12.0), y: CGFloat(5.0), width: CGFloat(100), height: CGFloat(10))
alert.addSubview(stepper)
alert.show()
UIAlertView is deprecated. You should use UIAlertController instead. Here is an answer that explains how you can implement what you want using a UIAlertController:
UIAlertController - add custom views to actionsheet
// Below is code for implementing UIAlertView Using UIAlertController in swift and add your custom views on it .
let logoutAlert = UIAlertController(title: "Alert", message: "DemoAlert", preferredStyle: UIAlertControllerStyle.alert)
logoutAlert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
logoutAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
// Write your code here
}))
var stepper = UIStepper()
stepper.frame = CGRect(x: CGFloat(12.0), y: CGFloat(5.0), width: CGFloat(100), height: CGFloat(10))
// You can add any view on UIAlert controller using below code:
logoutAlert.popoverPresentationController?.sourceRect = stepper.frame
logoutAlert.popoverPresentationController?.sourceView = stepper
self.present(logoutAlert, animated: true, completion: nil)

Add a label in UIAlertController?

I know that you can add a text field, but is it possible to add a label to a UIAlertController?
alertController.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Hyperlink"
inputTextField = textField
inputTextField?.text="www.google.com"
})
^^Textfield
There is function for you:
func showAlertWith(withLabel: String) {
let alert = UIAlertController(title: "Hello!", message: "Hi everybody!\n", preferredStyle: UIAlertController.Style.alert )
let action = UIAlertAction(title: "Ok", style: .default)
alert.addAction(action)
present(alert, animated: true, completion: {
// Add your label
let margin:CGFloat = 8.0
let rect = CGRect(x: margin, y: 72.0, width: alert.view.frame.width - margin * 2.0 , height: 20)
let label = UILabel(frame: rect)
label.text = withLabel
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
alert.view.addSubview(label)
})
}
I didn't bother too much with the coordinates and options of the label inside the alert, but I think that the general meaning is clear to you.
This may solve your issue in much easier and flexible way.
https://github.com/wimagguc/ios-custom-alertview
The addSubview is not available in UIAlertView since iOS7. The view hierarchy for this class is private and must not be modified.
As a solution, this class creates an iOS-style dialog which you can extend with any UIViews or buttons. The animations and the looks are copied too and no images or other resources are needed.

How do I add margins to UITextField in a UIAlertController?

I am currently implementing a UIAlertController with text inputs. I successfully made it without any issues. However, I want to change how it looks and especially add margins between textfields.
This is how it looks right now.
However I don't want these text fields that close. The question is, how do I add margins to textfields?
My code and attempt:
func createNameChangeSheet(){
var tvName : UITextField?
var tvSurname : UITextField?
let sheet = UIAlertController(title: "action", message: "alertView", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "OK", style: .Default) { (action) in
self.changeNameSurname((tvName?.text)!,surname: (tvSurname?.text)!)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
sheet.addAction(saveAction)
sheet.addAction(cancelAction)
sheet.addTextFieldWithConfigurationHandler { (textField) in
tvName = textField
textField.text = self.name
let margins = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0)
textField.layoutMargins = margins
}
sheet.addTextFieldWithConfigurationHandler { (textField) in
tvSurname = textField
textField.text = self.surname
}
self.presentViewController(sheet, animated: true) {}
}
in default UIAlertController views are not customizable, if you need customize output then we need to go for customviews or any thirdparty lib
An alternate to set bottom margin , make a UIView and addSubview to UITextField you can make an extension to use throughout the application.
extension UITextField {
func textbottommboarder(frame1 : CGRect){
let border = UIView()
let width = CGFloat(2.0)
border.backgroundColor = UIColor.lightGrayColor()
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: frame1.width, height: 2)
self.layer.addSublayer(border.layer)
self.layer.masksToBounds = true
}
}
and than use it on UITextfields
txt_username.textbottommboarder(txt_username.frame)

Resources