i have an AlertController with UITextView.
when UITexView become first responder the alter doesn't move up with the keyboard.
this is my code:
#IBAction func showAlert(sender: AnyObject) {
let alertController = UIAlertController(title: "Hello, I'm alert! \n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
let rect = CGRect(x: 15, y: 15, width: 240, height: 150)//CGRectMake(15, 50, 240, 150.0)
let textView = UITextView(frame: rect)
textView.font = UIFont(name: "Helvetica", size: 15)
textView.textColor = UIColor.lightGray
textView.backgroundColor = UIColor.white
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1.0
textView.text = "Enter message here"
textView.delegate = self
alertController.view.addSubview(textView)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let action = UIAlertAction(title: "Ok", style: .default, handler: { action in
let msg = (textView.textColor == UIColor.lightGray) ? "" : textView.text
print(msg!)
})
alertController.addAction(cancel)
alertController.addAction(action)
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
})
}
and this is my result:
there is a solution?
thanks in advance
just addTextField and then remove it
alert.addTextField { field in
field.translatesAutoresizingMaskIntoConstraints = false
field.heightAnchor.constraint(equalToConstant: 0).isActive = true
}
let inCntrlr = alert.childViewControllers[0].view!
inCntrlr.removeFromSuperview()
and then you could add your own views. here is a
result
After presenting alert controller. Open keyboard for TextView and move alert controller up.
I hope this will suite for you.
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
UIView.animate(withDuration: 0.5, animations: {
alertController.view.frame.origin.y = 100
})
})
UIAlertController by default will slide up when they keyboard is shown. The problem here is that you have added a subview to the alert controller. From the UIAlertController docs:
The UIAlertController 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.
Adding your own subview to the alert goes against what the docs say and is likely what is causing your problem. If you need an alert with a text view in it, your best bet is to create your own view and manage it yourself.
I created this drop-in replacement, also customizable for any special needs of course. It's pretty simple and 'just works'!
https://gist.github.com/unixb0y/42a1ae0fb707bdb5e1e484bafd33d44a
It is a subclass of UIAlertController with a UITextView inside.
When it is initialized, it observes keyboard changes and adjusts its view.frame.origin.y accordingly.
var keyboardHeight: CGFloat = 100 {
didSet {
let height = UIScreen.main.bounds.height
let menu = self.view.frame.height
let keyb = self.keyboardHeight
self.view.frame.origin.y = height-menu-keyb-20
}
}
...
...
...
#objc func keyboardChange(sender: Notification) {
guard let userInfo = sender.userInfo else { return }
let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
keyboardHeight = endFrame?.height ?? 100
}
It's like. You open keyboard and change alert position.
var alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
var alertControllerPositon:CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
#IBAction func showAlert(sender: AnyObject) {
let alertController = UIAlertController(title: "Hello, I'm alert! \n\n\n\n\n\n\n", message: "", preferredStyle: .alert)
let rect = CGRect(x: 15, y: 15, width: 240, height: 150)//CGRectMake(15, 50, 240, 150.0)
let textView = UITextView(frame: rect)
textView.font = UIFont(name: "Helvetica", size: 15)
textView.textColor = UIColor.lightGray
textView.backgroundColor = UIColor.white
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1.0
textView.text = "Enter message here"
textView.delegate = self
alertController.view.addSubview(textView)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let action = UIAlertAction(title: "Ok", style: .default, handler: { action in
let msg = (textView.textColor == UIColor.lightGray) ? "" : textView.text
print(msg!)
})
alertController.addAction(cancel)
alertController.addAction(action)
self.present(alertController, animated: true, completion: {
textView.becomeFirstResponder()
})
alertControllerPositon = alertController.view.frame.origin.y
}
#objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
alertControllerPositon = alertController.view.frame.origin.y
let result = self.view.frame.height - (alertController.view.frame.height + alertController.view.frame.origin.y) - 20
self.alertController.view.frame.origin.y -= (keyboardSize.height - result)
}
}
#objc func keyboardWillHide(notification: NSNotification) {
if self.alertController.view.frame.origin.y != alertControllerPositon {
self.alertController.view.frame.origin.y = alertControllerPositon
}
}
Related
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 a func it wants to use in other class files
I declare the func to be outside, This method I want to use it in the other two class files , But its not work , Is it where I got it wrong?
class BlurEffect{
var blurEffectView: UIVisualEffectView!
func blurEffectAnimation(isBlur: Bool, view: UIView) {
if isBlur {
let blurEffect = UIBlurEffect(style: .light)
blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)
UIView.animate(withDuration: 1.0){
self.blurEffectView.alpha = 0.4
self.blurEffectView.transform = CGAffineTransform.identity
}
} else {
blurEffectView.removeFromSuperview()
blurEffectView.effect = nil
}
}
}
I declare the BlurEffect method in this category
class ItemCardTableViewController: UITableViewController {
var blurEffectView: BlurEffect?
#objc func addNewItem() {
blurEffectView?.blurEffectAnimation(isBlur: true)
let addAlert = UIAlertController(title: "", message: "", preferredStyle: .alert)
addAlert.addTextField { (textfied: UITextField) in
textfied.addTarget(addAlert, action: #selector(addAlert.textDidChanged), for: .editingChanged)
}
let confirm = UIAlertAction(title: "ok", style: .default) { (action: UIAlertAction) in
guard let title = addAlert.textFields?.first?.text else { return }
let newItem = ItemCard(title: title, isFinish: false)
self.dataManager.items.append(newItem)
let indexPath = IndexPath(row: self.itemCardTableView.numberOfRows(inSection: 0), section: 0)
self.itemCardTableView.insertRows(at: [indexPath], with: .left)
self.blurEffectView?.blurEffectAnimation(isBlur: false)
}
let cancel = UIAlertAction(title: "cancle", style: .cancel) { _ in self.blurEffectView?.blurEffectAnimation(isBlur: false)}
addAlert.addAction(cancel)
confirm.isEnabled = false
addAlert.addAction(confirm)
self.present(addAlert, animated: true, completion: nil)
}
}
blurEffectView?.blurEffectAnimation(isBlur: true) it's not work
I am trying to get all the elements (UItextfields) that I have in defined in myScrollView in class AddViewController to another FormViewController where I have just an empty getFormView scrollview where I want to get all the elements of myScrollView to be appear, whether in a form of copy or getting that same.
I am adding subview of myScrollView to getFormView but this gives me error
unexpectedly found nil while unwrapping an optional
I am creating textfields by getting an input, like if set input to 7 the seven textfields will be generated in form and by clicking on creating I want these testfields should be in formViewController's uiscrollview that is getformview
FormViewController
import UIKit
class FormViewController: UIViewController {
#IBOutlet weak var menu: UIBarButtonItem!
#IBOutlet weak var getFormView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
menu.target = revealViewController()
menu.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
getFormView.alwaysBounceVertical = true
getFormView.scrollsToTop = true
getFormView.isScrollEnabled = true
getFormView.contentSize = CGSize(width: 343, height: 1500)
print("formViewController")
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
self.view.addSubview(self.getFormView)
self.getFormView.addSubview(desController.myScrollView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
AddViewController Image of my myScrollView
enter image description here
FormViewController image of getFormView
enter image description here
AddViewController
import UIKit
class AddViewController: UIViewController {
var templateName : String?
var templateDesc : String?
var noButtons : Int?
var noTextFields : Int?
var noLabels : Int?
var xValue = 20, yValue = 100
var tagNo = 0
var textObjects : Array<Any>?
var incrementerText : Int?
var xButton = 15 , yButton = 90
var tagButton = 10
var buttonObject : Array<Any>?
var buttonIncreament : Int?
var xLabel = 10 , yLabel = 80
var tagLabel = 15
var labelObject : Array<Any>?
var labelIncreament : Int?
#IBOutlet weak var menu: UIBarButtonItem!
#IBOutlet weak var myScrollView: UIScrollView!
#IBOutlet weak var reset: UIButton!
#IBAction func reset(_ sender: Any) {
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "AddViewController") as! AddViewController
let newFrontViewController = UINavigationController.init(rootViewController:desController)
revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}
#IBOutlet weak var createForms: UIButton!
#IBAction func createForms(_ sender: Any) {
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle : nil)
let desController = mainStoryBoard.instantiateViewController(withIdentifier: "FormViewController") as! FormViewController
// desController.getFormView.addSubview(myScrollView)
let newFrontViewController = UINavigationController.init(rootViewController:desController)
revealViewController().pushFrontViewController(newFrontViewController, animated: true)
}
#IBAction func addForm(_ sender: Any) {
let alertController = UIAlertController(title: "Create Template", message: "", preferredStyle: .alert)
alertController.extendedLayoutIncludesOpaqueBars = true
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = .default
textField.autocorrectionType = .default
textField.placeholder = "Title"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
//textField.keyboardAppearance = .dark
textField.keyboardType = .default
textField.autocorrectionType = .default
textField.placeholder = "Description"
textField.clearButtonMode = .whileEditing
}
let okAction = UIAlertAction(title: "Continue", style: UIAlertActionStyle.default) {
UIAlertAction in
print("Ok action")
let templateText = alertController.textFields![0]
let descriptionText = alertController.textFields![1]
self.templateName = templateText.text!
self.templateDesc = descriptionText.text!
if self.templateName?.isEmpty == false && self.templateDesc?.isEmpty == false {
print("Template: \(templateText.text!)\nDescription: \(descriptionText.text!)")
print("\(String(describing: self.templateName!)), \(String(describing: self.templateDesc!))")
self.dismiss(animated: true, completion: nil)
self.drawPop()
}
else {
self.okAlert()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) {
UIAlertAction in
self.dismiss(animated: true, completion: nil)
NSLog("Cancel Pressed")
}
//alertController.addAction(alertActionOkay)
// Add the actions
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// alertController.willChangeValue(forKey: "Continue")
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
func drawPop() {
let alertController = UIAlertController(title: "\(self.templateName!)", message: "\(self.templateDesc!)", preferredStyle: .alert)
//attributing textfields labels
alertController.addTextField { (textField: UITextField) in
//textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
// textField.keyboardType = .default
textField.placeholder = "TextFileds"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
textField.autocorrectionType = .default
textField.placeholder = "Buttons"
textField.clearButtonMode = .whileEditing
}
alertController.addTextField { (textField: UITextField) in
// textField.keyboardAppearance = .dark
textField.keyboardType = UIKeyboardType.numberPad
textField.autocorrectionType = .default
textField.placeholder = "Labels"
textField.clearButtonMode = .whileEditing
}
// Create the actions
let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
let notextFieldText = alertController.textFields![0]
let noButtonText = alertController.textFields![1]
let noLabelText = alertController.textFields![2]
self.noTextFields = Int(notextFieldText.text!)
self.noButtons = Int(noButtonText.text!)
self.noLabels = Int(noButtonText.text!)
print("Template: \(notextFieldText.text!)\nDescription: \(noButtonText.text!)")
print("\(noLabelText.text!)")
print("\(String(describing: self.noTextFields!)), \(String(describing: self.noButtons!)) , \(String(describing: self.noLabels!))")
self.createForms.isHidden = false
self.myScrollView.isHidden = false
self.reset.isHidden = false
self.incrementerText = 20
if self.noTextFields! > 0 {
for _ in 0..<self.noTextFields! {
print ("hello")
let sampleTextField = UITextField(frame: CGRect(x: self.xValue, y: self.yValue, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
sampleTextField.tag = self.tagNo
// self.view.addSubview(sampleTextField)
//trying to print at container view
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleTextField)
let frametext = sampleTextField.frame.size.height
self.textObjects?.append(sampleTextField)
self.yValue = self.yValue + Int(frametext) + 20
self.xValue = 20
}
}
else {
print("no text field found")
}
self.buttonIncreament = 20
if self.noButtons! > 0 {
for _ in 0..<self.noButtons! {
print ("Buttons")
let sampleButton = UIButton(frame: CGRect(x: self.xButton, y: self.yButton, width: 150, height: 25))
sampleButton.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleButton.tag = self.tagNo
// self.view.addSubview(sampleButton)
let frametext = sampleButton.frame.size.height
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleButton)
self.buttonObject?.append(sampleButton)
self.yButton = self.yButton + Int(frametext) + 20
self.xButton = 20
}
}
else {
print("no button found")
}
self.labelIncreament = 20
if self.noLabels! > 0 {
for _ in 0..<self.noLabels! {
print ("Labels")
let sampleLabel = UILabel(frame: CGRect(x: self.xLabel, y: self.yLabel, width: 150, height: 25))
// sampleLabel.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleLabel.tag = self.tagNo
// self.view.addSubview(sampleButton)
let frameLabel = sampleLabel.frame.size.height
self.view.addSubview(self.myScrollView)
self.myScrollView.addSubview(sampleLabel)
self.labelObject?.append(sampleLabel)
self.yLabel = self.yLabel + Int(frameLabel) + 20
self.xLabel = 20
}
}
else {
print("no button found")
}
self.dismiss(animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) {
UIAlertAction in
self.dismiss(animated: true, completion: nil)
NSLog("Cancel Pressed")
}
//alertController.addAction(alertActionOkay)
// Add the actions
alertController.addAction(cancelAction)
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
func createForm() {
let sampleTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40))
sampleTextField.placeholder = "Enter text here"
sampleTextField.font = UIFont.systemFont(ofSize: 15)
sampleTextField.borderStyle = UITextBorderStyle.roundedRect
sampleTextField.autocorrectionType = UITextAutocorrectionType.no
sampleTextField.keyboardType = UIKeyboardType.default
sampleTextField.returnKeyType = UIReturnKeyType.done
sampleTextField.clearButtonMode = UITextFieldViewMode.whileEditing;
sampleTextField.contentVerticalAlignment = UIControlContentVerticalAlignment.center
sampleTextField.delegate = self as? UITextFieldDelegate
self.view.addSubview(sampleTextField)
}
func okAlert() {
let alertController = UIAlertController(title: "Oops!", message: "Enter required data", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
/*
let scrollmyView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.alwaysBounceVertical = true
scrollView.scrollsToTop = true
// myScrollView.alwaysBounceHorizontal = true
scrollView.isScrollEnabled = true
scrollView.contentSize = CGSize(width: 200, height: 1500)
return scrollView
}()
*/
override func viewDidLoad() {
super.viewDidLoad()
menu.target = revealViewController()
menu.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
myScrollView.alwaysBounceVertical = true
myScrollView.scrollsToTop = true
// myScrollView.alwaysBounceHorizontal = true
myScrollView.isScrollEnabled = true
myScrollView.contentSize = CGSize(width: 343, height: 1500)
// scroller.contentSize = CGSize(width: yourWidth, height: yourHeight)
createForms.isHidden = true
myScrollView.isHidden = true
reset.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Error
Full screen error
Why you are using scrollview if you have same type of elements. Best way is to use table view. We use scrollview if the elements in most of the rows are different. Once you use table view you don't have to copy anything.
Best approach for your problem:
If you have same type of view controller then you can use one view controller as AddViewController and FormViewController.
Create the same UITextFields in your FormViewController.
and when a user fills the form in AddViewController , update the textfields of your FormViewController with the text of AddViewController's text field
content.view.frame = CGRect(x: -UIScreen.main.bounds.size.width, y: 0, width: UIScreen.main.bounds.size.width, height: view.frame.size.height)
getFormView = content.scrollView
view.addSubview(content.scollView)
content.didMove(toParentViewController: self)
Here content is the view controller that you want to add in you case it is instance of AddViewController
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 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)