Get Keyboard Toolbar Height - swift

i have the same question as this :
iPhone Keyboard with accessory view height problems
but the answer has no new solution and does not solve anything!

I found a good solution Here
Made few changes and updated it to swift 4.2.
Few points to be mentioned
Created an outlet of textfield and bottom constraint from Storyboard to ViewController
Bottom constraint is used for moving the textfield up and down.
class ViewController: UIViewController {
#IBOutlet weak var inputField: UITextField!
#IBOutlet weak var textFieldBottomContraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.setUpKeyBoardNotifications()
self.addToolBarTo(uiElement: self.inputField)
}
func setUpKeyBoardNotifications()
{
NotificationCenter.default.addObserver(self,
selector: #selector(self.keyboardNotification(notification:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
}
func addToolBarTo(uiElement element:UITextField)
{
let numberToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 45))
numberToolbar.barStyle = .black
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelAction)),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneAction))]
numberToolbar.sizeToFit()
element.inputAccessoryView = numberToolbar
}
#objc func keyboardNotification(notification: NSNotification) {
if let userInfo = notification.userInfo {
let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let endFrameY = endFrame?.origin.y ?? 0
let duration:TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
let animationCurveRawNSN = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber
let animationCurveRaw = animationCurveRawNSN?.uintValue ?? UIView.AnimationOptions.curveEaseInOut.rawValue
let animationCurve:UIView.AnimationOptions = UIView.AnimationOptions(rawValue: animationCurveRaw)
if endFrameY >= UIScreen.main.bounds.size.height {
self.textFieldBottomContraint?.constant = 0.0
} else {
self.textFieldBottomContraint?.constant = endFrame?.size.height ?? 0.0
}
UIView.animate(withDuration: duration,
delay: TimeInterval(0),
options: animationCurve,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
#objc func cancelAction()
{
self.inputField.resignFirstResponder()
}
#objc func doneAction()
{
self.inputField.resignFirstResponder()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}

Related

Done/Cancel Button is not showing Issue In Toolbar(Simulator tested)

I added a toolbar with done and cancel button but the buttons are not appearing on the toolbar. I could not find the cause of this issue.
i tried many changes but the issue is not resolved.
This is the code regarding the toolbar:
#IBOutlet weak var textFieldYear: UITextField!
#IBOutlet weak var viewMonth: UIView!
#IBOutlet weak var textFieldMonth: UITextField!
#IBOutlet weak var viewDatePicker: UIView!
#IBOutlet weak var datePicker: UIPickerView!
func setUpDatePickerView(){
let date = Date()
arrYear.add(date.year)
if date.month == "November" || date.month == "December" {
let newDate = Calendar.current.date(byAdding: .year, value: 1, to: date)
arrYear.add(newDate?.year ?? "")
}
let toolBar = UIToolbar().ToolbarPiker(mySelect: #selector(self.donePicker), cancel: #selector(self.dismissPicker))
viewDatePicker.addSubview(toolBar)
datePicker.reloadAllComponents()
datePicker.selectRow(0, inComponent: 0, animated: true)
textFieldYear.text = (arrYear[0] as! String)
textFieldMonth.text = Calendar.current.date(byAdding: .month, value: 1, to: Date())?.month
}
// ToolBar
extension UIToolbar {
func ToolbarPiker(mySelect : Selector, cancel : Selector) -> UIToolbar {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.black
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: self, action: mySelect)
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
spaceButton.width = 225
let cancelButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: self, action: cancel)
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
return toolBar
}
}
#objc func donePicker() {
self.view.endEditing(true)
}
#objc func dismissPicker() {
self.view.endEditing(true)
viewDatePicker.isHidden = true
}
I think, you might be missing to add the toolbar as an accessory view to the input element. For example here we will add a toolbar as an accessory view to a textField.
textField1.inputAccessoryView = toolBar
Please let me know if it worked
I would subclass UITextField and add your pickerview and toolbar there:
import UIKit
class MonthField: UITextField, UIPickerViewDelegate, UIPickerViewDataSource {
let pickerView = UIPickerView()
var dataSource: [String] { return Calendar.current.monthSymbols }
var month: Int = 0
func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return dataSource.count }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return dataSource[row] }
// Configure toolbar and picker view
override func didMoveToWindow() {
let toolbar = UIToolbar()
toolbar.setItems([
.init(title: "Cancel", style: .plain, target: self, action: #selector(cancel)),
.flexibleSpace,
.init(title: "Done", style: .plain, target: self, action: #selector(done)),
], animated: false)
pickerView.delegate = self
pickerView.dataSource = self
pickerView.selectRow(Date().month-1, inComponent: 0, animated: false)
inputView = pickerView
inputAccessoryView = toolbar
toolbar.sizeToFit()
placeholder = "Select Month"
}
override func caretRect(for position: UITextPosition) -> CGRect { return .zero }
#objc func done(_ barButtonItem: UIBarButtonItem) {
month = pickerView.selectedRow(inComponent: 0) + 1
text = dataSource[month-1]
endEditing(false)
}
#objc func cancel(_ barButtonItem: UIBarButtonItem) {
endEditing(false)
}
}
extension UIBarButtonItem {
static let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
}
extension Date {
var month: Int { return Calendar.current.component(.month, from: self) }
}

Can't dismiss KeyBoard when a Done button pressed in UITableViewCell

First, done button codes are below
class ViewController: UIViewController, UITextFieldDelegate {
let inputNumber = UITextField(frame: CGRect(x: 150.0, y: 100.0, width: 200.0, height: 50.0))
let toolBarKeyBoard = UIToolbar()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
var result : String!
override func viewDidLoad() {
super.viewDidLoad()
calculatePrice()
}
func calculatePrice () {
priceInputLabel.keyboardType = .numberPad
priceInputLabel.clearButtonMode = .whileEditing
self.view.addSubview(priceInputLabel)
toolBarKeyBoard.sizeToFit()
toolBarKeyBoard.setItems([flexibleSpace, doneButton], animated: false)
priceInputLabel.inputAccessoryView = toolBarKeyBoard
}
#objc func donePressed() {
view.endEditing(true)
}
}
It works OK. When I touch 'inputNumber(UITextField)', a keyboard pops up. And when I input Number and touch 'Done' button, a keyboard dismisses. Good.
But, in other codes, down below, doesn't work.
class FruitTableViewCell: UITableViewCell, UITextFieldDelegate {
var fruitsTextField = UITextField()
let toolBarKeyBoard = UIToolbar()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
var result : String!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(fruitsTextField)
}
override func layoutSubviews() {
super.layoutSubviews()
fruitsTextField.frame = CGRect(x: 250, y: 7.5, width: 100, height: 30)
fruitsTextField.textColor = UIColor(red: CGFloat(242/255.0), green: CGFloat(56/255.0), blue: CGFloat(90/255.0), alpha: 1.0)
fruitsTextField.keyboardType = .numberPad
fruitsTextField.clearButtonMode = .whileEditing
toolBarKeyBoard.sizeToFit()
fruitsTextField.inputAccessoryView = toolBarKeyBoard
toolBarKeyBoard.setItems([flexibleSpace, doneButton], animated: false)
}
#objc func donePressed() {
fruitTextField.endEditing(true)
}
I can build, I can toggle a keyboard, I can touch a done button, but it doesn't dismiss a keyboard.
I think, the function '#objc func donePressed()' at the bottom line is matter.
First codes are 'view.endEditing(true)' but these are 'fruitTextField.endEditing(true)'
So, I tried to change codes.
#objc func donePressed() {
contentView.endEditing(true)
}
But doesn't work.
Question1. How can I dismiss a keyboard?
Question2. Why doesn't a keyboard dismiss even though I touched 'Done' button?
Question3. In second code, is a keyboard not the FirstResponder?
Question4. In second code, what is the View for '.endEditing'?
Thanks!
Change your "done button" initialization to:
lazy var doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
You need target: self, and you need it to be lazy in order for self to be valid when the button is instantiated.
You can also change your done func to:
#objc func donePressed() {
fruitsTextField.resignFirstResponder()
}
Doesn't really change the functionality, but I believe it is the recommended method.

Swift Unexpectedly found nil while unwrapping an Optional value while pass image to another ViewController

I have two VCs. The first one contains an imagePicker from gallery and a callback function that sends and image to the chatLog... I want to send the selected photo to the 2nd VC
if let selectedImage = selectedImageFromPicker {
//self.callback?(selectedImage)
detailImageViewController.aImage = selectedImage
}
I created the 2nd VC as controller for PreviewImage with buttons cancel or accept. I tried to pass the image displayed on the 2nd VC back to 1st VC this way but it shows me:
Fatal error: Unexpectedly found nil while unwrapping an Optional value.
How can I fix that?
var t : EVTPhotoTekingHelper!
#objc func actionSend() {
if aImage != nil{
t.callback?(aImage!)
}
else {
print("nil")
}
dismiss(animated: true, completion: nil)
}
UPDATED:
My 1st VC
typealias PhotoTekingHelperCallBack = (UIImage?) -> ()
class EVTPhotoTekingHelper: NSObject {
// View controller on which AlertViewController and UIImageViewController are present
weak var viewController: UIViewController!
var imagePickerController: UIImagePickerController?
var callback: PhotoTekingHelperCallBack?
var photoTakinHelper: EVTPhotoTekingHelper!
// MARK: - Initialization
init(viewController: UIViewController, callback: #escaping PhotoTekingHelperCallBack) {
self.viewController = viewController
self.callback = callback
super.init()
showPhotoSourceSelection()
}
func showPhotoSourceSelection() {
let alertController = UIAlertController.init(title: nil,
message: "Message?",
preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let photoLibraryAction = UIAlertAction(title: "from library", style: .default) { (action) in
self.showImagePickerController(sourceType: .photoLibrary)
}
alertController.addAction(cancelAction)
alertController.addAction(photoLibraryAction)
if UIImagePickerController.isFlashAvailable(for: .rear) {
let cameraAction = UIAlertAction.init(title: "from camera", style: .default, handler: { (action) in
self.showImagePickerController(sourceType: .camera)
})
alertController.addAction(cameraAction)
}
viewController.present(alertController, animated: true, completion: nil)
}
func showImagePickerController(sourceType: UIImagePickerControllerSourceType) {
imagePickerController = UIImagePickerController.init()
imagePickerController!.sourceType = sourceType
imagePickerController!.delegate = self
viewController.present(imagePickerController!, animated: true, completion: nil)
}
}
Extension from 1st VC
extension EVTPhotoTekingHelper: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var selectedImageFromPicker: UIImage?
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
selectedImageFromPicker = editedImage
} else if let originImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
selectedImageFromPicker = originImage
}
let detailImageViewController = EVImagePreviewController()
let ncDetailImageViewController = UINavigationController(rootViewController: detailImageViewController)
if let selectedImage = selectedImageFromPicker {
//self.callback?(selectedImage)
detailImageViewController.aImage = selectedImage
}
viewController.dismiss(animated: false, completion: nil)
viewController.parent?.present(ncDetailImageViewController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
viewController.dismiss(animated: false, completion: nil)
}
}
My 2nd VC
class EVImagePreviewController: UIViewController, UIScrollViewDelegate {
var t : EVTPhotoTekingHelper!
var aImageView: UIImageView!
var aImage: UIImage!
private var aScrollView: UIScrollView!
override func viewDidAppear(_ animated: Bool) {
aImageView = UIImageView(frame: CGRect(x: 0, y: 75, width: (aImage?.size.width)!, height: (aImage?.size.height)!))
aImageView.contentMode = .scaleAspectFit
aImageView.image = aImage
aScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
aScrollView.backgroundColor = .clear
aScrollView.contentSize = CGSize(width: view.frame.size.width, height: view.frame.height)
aScrollView.minimumZoomScale = 0.2
aScrollView.maximumZoomScale = 2.3
aScrollView.clipsToBounds = true
aScrollView.delegate = self
aScrollView.addSubview(aImageView)
view.addSubview(aScrollView)
aImageView.center = CGPoint(x: aScrollView.bounds.midX, y: aScrollView.bounds.midY - 35)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(actionSend))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(actionBack))
}
// MARK: - IBAction
#objc func actionBack() {
dismiss(animated: false, completion: nil)
}
#objc func actionSend() {
print("\(t)")
if aImage != nil{
t.callback?(aImage!)
}
else {
print("nil")
}
//self.callback?(aImage)
dismiss(animated: true, completion: nil)
}
// MARK: - UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return aImageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let subView = scrollView.subviews[0]
let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0.0)
let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0.0)
subView.center = CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY)
}
}
Here you dismiss your first view controller before you present your 2nd one from the parent of your first view controller:
viewController.dismiss(animated: false, completion: nil)
To me so far doesn't make sense. Its not clear where is the callback implementation is.
My guess that the nil exception is not for the UIImage for sure. its somewhere
inside your callback implementation.

Swift- shifting text field issue

I have 2 text fields both placed on top of a image view. The bottom text field is supposed to shift up when the keyboard appears. When the image view is empty the bottom text field shifts up as expected, but when image is present in image view, the bottom text field doesn't shift up. when executing can see with help of print statements that keyboardWillShow function is not executing. can anyone help here?
Following is my code
class ViewController: UIViewController, UITextFieldDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet weak var actualImage: UIImageView!
#IBOutlet weak var shareButton: UIButton!
#IBOutlet weak var deleteButton: UIButton!
#IBOutlet weak var topTextField: UITextField!
#IBOutlet weak var bottomTextField: UITextField!
var activeTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
topTextField.delegate = self
bottomTextField.delegate = self
//Animations
topTextField.isHidden = true
bottomTextField.isHidden = true
shareButton.isEnabled = false
deleteButton.isEnabled = false
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//Editing text Fields
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
}
#objc func keyboardDidShow(notification: Notification) {
print("keyboarddidshow")
if activeTextField != nil {
let info: NSDictionary = notification.userInfo! as NSDictionary
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
let keyboardY = self.view.frame.size.height - keyboardSize.height
let textFieldY: CGFloat! = self.activeTextField.frame.origin.y
if self.view.frame.origin.y >= 0{
if textFieldY > (keyboardY - 80){
UIView.animate(withDuration: 0.25,delay:0.0,options:UIViewAnimationOptions.curveEaseIn, animations: {
self.view.frame = CGRect(x: 0, y: self.view.frame.origin.y - (textFieldY - (keyboardY - 80)), width: self.view.bounds.width, height: self.view.bounds.height)
}, completion: nil)
}
}
}
}
#objc func keyboardWillHide(notification: Notification){
print("switch field keyboard will hide")
UIView.animate(withDuration: 0.25,delay:0.0,options:UIViewAnimationOptions.curveEaseIn, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height)}, completion: nil
)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func viewDidDisappear(_ animated: Bool) {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//share button pressed
#IBAction func sharePressed(_ sender: UIButton) {
topTextField.borderStyle = .none
topTextField.borderStyle = .none
let image: UIImage = generateMemedImage()
let shareImage = UIActivityViewController(activityItems: [image, topTextField,bottomTextField], applicationActivities: nil)
present(shareImage, animated: true, completion: nil)
}
//allow selecting image from photo library
#IBAction func selectFromGallery(_ sender: Any) {
let gallery = UIImagePickerController()
gallery.delegate = self
gallery.sourceType = .photoLibrary
present(gallery, animated: true, completion: nil)
}
#IBAction func selectFromCamera(_ sender: Any) {
let gallery = UIImagePickerController()
gallery.delegate = self
if UIImagePickerController.isSourceTypeAvailable(.camera){
gallery.sourceType = .camera
present(gallery, animated: true, completion: nil)
} else {
displayAlert(title: "Camera not available", message: "")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
actualImage.image = selectedImage
dismiss(animated: true, completion: nil)
topTextField.isHidden = false
bottomTextField.isHidden = false
shareButton.isEnabled = true
deleteButton.isEnabled = true
topTextField.text = " "
bottomTextField.text = " "
}
#IBAction func deletePressed(_ sender: Any) {
actualImage.image = nil
topTextField.isHidden = true
bottomTextField.isHidden = true
shareButton.isEnabled = false
deleteButton.isEnabled = false
topTextField.text = " "
bottomTextField.text = " "
}
//display alert
func displayAlert(title: String, message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
func generateMemedImage() -> UIImage {
// Render view to an image
UIGraphicsBeginImageContextWithOptions(CGSize(width: 375, height: 517), false, 0)
view.drawHierarchy(in: CGRect(x: 0, y: -75, width: view.bounds.size.width, height: view.bounds.size.height), afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return memedImage
}
}
When you show the camera or the gallery, viewDidDisappear is called, which removes your subscription to the notifications. Perhaps you should subscribe to the notifications in viewDidAppear like thus:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self, selector: #selector(keyboardDidShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
center.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

Creating Sign Up View page in SWIFT with A UIImage profile picture setup, Using NEXT as Return Key and UIImage setup not working

I am building an app with which my focus is on User Friendly.
In the SignUpViewController, i have a profilePic of type UIImage, Four standard UITextFields to record user's data, and Two more UITextField which activates a UIDatePicker and a UIPicker.
I'm experiencing some problems such as;
1) The UIImage doesn't clip to bounds to give it the round sort of look
2) When i use the UIImage to fetch image from my gallery, it doesn't give me the option to scale my image size and rather gives me a static image pick
3) My UITextFields don't respond to the Next settings i have used. Again, the next setting has been implemented in my LogInViewController and works perfectly. But why isn't it working in the SignUpViewController?
A big thank you in advance.
import UIKit
import Parse
class SignUpViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var profilePic: UIImageView!
#IBOutlet weak var firstName: UITextField!
#IBOutlet weak var lastName: UITextField!
#IBOutlet weak var signUpEmail: UITextField!
#IBOutlet weak var signUpPassword: UITextField!
#IBOutlet weak var dateTextField: UITextField!
#IBOutlet weak var genderTextField: UITextField!
var datePicker:UIDatePicker!
var genderPicker:UIPickerView!
var genderSelect = ["Male", "Female"]
override func viewDidLoad() {
super.viewDidLoad()
// PROFILE PICTURE
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
profilePic.frame = CGRect(x: 10, y: 170, width: 80, height: 80)
profilePic.layer.cornerRadius = profilePic.frame.size.width / 2
profilePic.clipsToBounds = true
// UI DATE PICKER SETUP
var customView:UIView = UIView(frame: CGRectMake(0, 100, 320, 160))
customView.backgroundColor = UIColor.clearColor()
datePicker = UIDatePicker(frame: CGRectMake(0, 0, 320, 160))
datePicker.datePickerMode = UIDatePickerMode.Date
datePicker.maximumDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitYear, value: -16, toDate: NSDate(), options: nil)
customView.addSubview(datePicker)
dateTextField.inputView = customView
var dateToolBar = UIToolbar()
dateToolBar.barStyle = UIBarStyle.Default
dateToolBar.translucent = true
dateToolBar.tintColor = UIColor(red: 246/255, green: 141/255, blue: 17/255, alpha: 1)
dateToolBar.sizeToFit()
dateTextField.inputAccessoryView = dateToolBar
var doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "datePickerSelected")
var spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPicker")
dateToolBar.setItems([cancelButton, spaceButton, doneButton], animated: true)
dateToolBar.userInteractionEnabled = true
// UI GENDER PICKER VIEW
genderPicker = UIPickerView(frame: CGRectMake(0, 0, 320, 160))
genderPicker.showsSelectionIndicator = true
var customGenderView:UIView = UIView(frame: CGRectMake(0, 100, 320, 160))
customGenderView.backgroundColor = UIColor.clearColor()
customGenderView.addSubview(genderPicker)
genderTextField.inputView = customGenderView
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 246/255, green: 141/255, blue: 17/255, alpha: 1)
toolBar.sizeToFit()
genderPicker.delegate = self
genderPicker.dataSource = self
var doneBtn = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
var spaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
var cancelBtn = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelPicker")
toolBar.setItems([cancelBtn, spaceBtn, doneBtn], animated: true)
toolBar.userInteractionEnabled = true
genderTextField.inputView = genderPicker
genderTextField.inputAccessoryView = toolBar
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if let nextField = textField.nextField {
nextField.becomeFirstResponder()
}
return true
}
// UIIMAGE TO FUNCTION AS BUTTON WHEN TAPPED
func imageTapped(gesture:UIGestureRecognizer) {
if let profilePic = gesture.view as? UIImageView {
showActionSheet()
}
}
func camera() {
var myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
//myPickerController.allowsEditing = true
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
myPickerController.allowsEditing = true
//myPickerController.setEditing(true, animated: true)
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject: AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
// DATE FORMATTING AND CHOOSING
func datePickerSelected() {
dateTextField.text = datePicker.date.description
dateTextField.text = self.dateformatterDate(datePicker.date) as String
dateTextField.resignFirstResponder()
}
func dateformatterDate(date: NSDate) ->NSString {
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
return dateFormatter.stringFromDate(date)
}
// GENDER SELECT
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView:UIPickerView, numberOfRowsInComponent component: Int) ->Int {
return genderSelect.count
}
func pickerView(pickerView:UIPickerView, titleForRow row:Int, forComponent component:Int) -> String! {
return genderSelect[row]
}
func pickerView(pickerView:UIPickerView, didSelectRow row:Int, inComponent component:Int) {
genderTextField.text = genderSelect[row]
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return false
}
func genderPickerSelected() {
genderTextField.text = genderPicker.description
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
#IBAction func signUpBtn(sender: AnyObject) {
}
}
1.
Tell the imageView to clip to bounds after image assignment. I also suggest altering it's content mode accordingly if desired (aspect fill, fit, etc.)
Edit: Also reset the corner radius.
You need to scale images yourself in your didFinishPickingMediaWithInfo method. There are lots of different ways to do this, about halfway down this page is one I used a few times: http://www.raywenderlich.com/93276/implementing-tesseract-ocr-ios
Did you set the textFieldNameHere.delegate = self anywhere? I couldn't spot it.