Swift Hides back button - swift3

I want to hide the back button and set a title.
I'm using the following code:
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Einstellungen"
navigationItem.hidesBackButton = true }
But the title isn't shown and the back button is still there but if I touch it nothing happens. Can anybody help me please?

I found a solution on my own.
If I'm setting the title and the hidesBackButton from my previous ViewController everything works fine.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVC = segue.destination as? ViewControllerFirstSettings {
destinationVC.navigationItem.hidesBackButton = true
destinationVC.navigationItem.title = "Einstellungen"
}
}

This code may help :
// MARK: - CUSTOM METHODS
func createNavBar() {
let leftNavigationButton = UIButton()
leftNavigationButton.setImage(UIImage(named: "ic_back.png"), forState: .Normal)
leftNavigationButton.frame = CGRectMake(10, 10, 20, 15)
leftNavigationButton.addTarget(self, action: "onBackButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
let customBarItem = UIBarButtonItem(customView: leftNavigationButton)
self.navigationItem.leftBarButtonItem = customBarItem;
//set TitleAppIcon
let GR = UITapGestureRecognizer(target: self, action: Selector("headerLogoTapAction:"))
let imageView = UIImageView(frame: CGRect(x: 90, y: 0, width: ((UIScreen.mainScreen().bounds.width)/3), height: 40))
imageView.addGestureRecognizer(GR)
imageView.userInteractionEnabled = true
navigationItem.titleView = imageView
}

Related

Reset CollectionviewCell position on tap gesture

I am working with gestures first time here. Please let me know if my approach is wrong or any better solution.
I am trying to delete the collectionView Cell on swiping Left just like UITableview delete function. Deleting works fine. Now what I want is, Once I swipe the cell and tap anywhere on COllectionView it should swipe back to its original position(same like tableview delete row functionality)
I am using/trying this code
Updated viewDidLoad and tapped event
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
self.view.addGestureRecognizer(tap)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CustomCell
Cell.backgroundColor = UIColor.white
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(delete(sender:)))
leftSwipe.direction = UISwipeGestureRecognizerDirection.left
Cell.addGestureRecognizer(leftSwipe)
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
Cell.addGestureRecognizer(tap)
Cell.deleteButton.addTarget(self, action: #selector(DeleteCell(sender:)), for: .touchUpInside)
}
func tapped(_ recognizer: UITapGestureRecognizer) {
// self.collectionView.performBatchUpdates({
//self.collectionView.reloadSections(NSIndexSet(index: 0) as IndexSet)
//}, completion: nil)
let point = recognizer.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: point)
let cell = self.collectionView.cellForItem(at: indexPath!)
UIView.animate(withDuration: 0.4) {
cell?.contentView.frame = CGRect(x: 0, y: 0, width: (cell?.contentView.frame.width)!, height: (cell?.contentView.frame.height)!)
}
}
func delete(sender: UISwipeGestureRecognizer){
let cell = sender.view as! CustomCell
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: -90, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
}
func DeleteCell(sender : AnyObject){
let cell = sender.superview as! CustomCell
let i = self.collectionView.indexPath(for: cell)!.item
let indexpath = self.collectionView.indexPath(for: cell)
let array : NSMutableArray = []
self.collectionView.performBatchUpdates({
self.userArray.remove(at: i)
array.add(indexpath!)
self.collectionView.deleteItems(at:array as! [IndexPath])
}, completion: nil)
}
class CustomCell: UICollectionViewCell {
let deleteButton: UIButton = {
let deleteBtn = UIButton()
deleteBtn.setImage(UIImage(named: "red"), for: .normal)
deleteBtn.contentMode = .scaleAspectFit
return deleteBtn
}()
}
So here I am able to set the cell's position back to original by self.collectionView.performBatchUpdates but its not smooth animation. I tried using
UIView.animate(withDuration: 0.4) {
cell.contentView.frame = CGRect(x: 0, y: 0, width: cell.contentView.frame.width, height: cell.contentView.frame.height)
}
but it works only if swiped cell tapped, not any other cell or anywhere else. Any suggestions would be helpful!!
Right now you are accessing your cell from within itself. The reason it only works to tap on the cell you just swiped is because that is the only cell with that specific instance of UITapGestureRecognizer. To fix this, you should add that tap gesture recognizer to your whole view. Try adding this to your viewDidLoad() method:
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
self.view.addGestureRecognizer(tap)
Finally, got the solution.
Here is the demo project I found - CollectionViewSlideLeft
Hope it will help someone like me. :)

How Can I Pass the Value of A Textfield to a Button Clicked Function in Swift3?

I need to preform username and login checks upon pressing the login button. I need to do all of this with programmatically. Anyhow, my problem is that when I create a button that connects to a function, the textfields are then out of scope.
import UIKit
class ViewController: UIViewController {
var usernameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let usernameTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
usernameTextField.center = CGPoint(x: 160, y: 80)
usernameTextField.placeholder = "username"
usernameTextField.text = ""
usernameTextField.borderStyle = UITextBorderStyle.line
usernameTextField.backgroundColor = UIColor.white
usernameTextField.textColor = UIColor.blue
self.view.addSubview(usernameTextField)
let button = UIButton(type: UIButtonType.system) as UIButton
let xPostion:CGFloat = 10
let yPostion:CGFloat = 200
let buttonWidth:CGFloat = 150
let buttonHeight:CGFloat = 45
button.frame = CGRect(x:xPostion, y:yPostion, width:buttonWidth, height:buttonHeight)
button.backgroundColor = UIColor.lightGray
button.setTitle("Submit", for: UIControlState.normal)
button.tintColor = UIColor.black
button.addTarget(self, action: #selector(ViewController.buttonAction(_:)), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(_ sender:UIButton!) {
let username = usernameTextField.text
print("Username value is \(String(describing: username))!")
print("Button tapped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
How can I get a usernameTextField at buttonAction function ?
usernameTextField is not out of scope, your app will just crash since you have hidden the property of that name with a local variable inside viewDidLoad.
You should change your let-line to usernameTextField = which does not create a local variable of the same name but assigns something to the property instead:
override func viewDidLoad() {
super.viewDidLoad()
usernameTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
usernameTextField.center = CGPoint(x: 160, y: 80)
usernameTextField.placeholder = "username"
usernameTextField.text = ""
usernameTextField.borderStyle = UITextBorderStyle.line
usernameTextField.backgroundColor = UIColor.white
usernameTextField.textColor = UIColor.blue
self.view.addSubview(usernameTextField)
...
}

How to add spacing to Left BarButtonItem Image with Swift 3

I would like to add space to the left of the bar button.
So, I add this code.
navbar.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin, .flexibleRightMargin]
navbar.delegate = self
UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green:49.0/255.0, blue:79.0/255.0, alpha:0.1)
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().isTranslucent = true
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
navItem.title = prefs.value(forKey: "PROVIDER_NAME") as! String?
let image = UIImage(named: "back_image")
navItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(addTapped))
After adding this code, the button image does not show well and looks no good.
Could anyone help me to solve this problem?
Hi Code given below might be useful for you.
extension UIBarButtonItem {
class func itemWith(colorfulImage: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem {
let button = UIButton(type: .custom)
button.setImage(colorfulImage, for: .normal)
button.frame = CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -50, 0, 0)
button.addTarget(target, action: action, for: .touchUpInside)
let barButtonItem = UIBarButtonItem(customView: button)
return barButtonItem
}
}
You can increase or decrease Left Padding for UIEdgeInsetsMake(0, -50, 0, 0) as per your requirement for left padding.
You can use above extension in your code as describe below.
self.navigationItem.leftBarButtonItem = UIBarButtonItem.itemWith(colorfulImage: UIImage(named: "ic_back")?.withColor(UIColor.white), target: self, action: #selector(btnBackClicked))
func btnBackClicked() {
print("your code here on back button tapped.")
}

Swift 3.0 - Hide keyboard for multiple UItextfield

I have 5 UITextFields, everytime I clicked on the textfield, keyboard appeared. when user touch outside of the textfield, keyboard will hide. However, there is one special textField is for Pop Up. When Pop up appear, the previous textfield couldn't hide the keyboard. How am I gonna hide the keyboard first, and then show the pop up?
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == self.customerAddress{
scrollView.setContentOffset(CGPoint(x: 0,y:5), animated: true)
}
else if textField == self.district{
textField.resignFirstResponder()
scrollView.setContentOffset(CGPoint(x: 0,y:20), animated: true)
visualEffectView.isHidden = false
districtpicker.selectRow(3, inComponent: 0, animated: false)
self.view.addSubview(districtPopUp)
districtPopUp.center = self.subView.convert(CGPoint(x:subView.frame.size.width/2,y:subView.frame.size.height/3), to: subView)
districtPopUp.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
UIView.animate(withDuration: 0.4, animations: {
self.visualEffectView.alpha = 0.5
self.districtPopUp.alpha = 1
self.districtPopUp.transform = CGAffineTransform.identity
})
}
}
#IBAction func districtPopDismiss(_ sender: UIButton) {
scrollView.setContentOffset(CGPoint(x: 0,y:-64), animated: true)
UIView.animate(withDuration: 0.3, animations: {
self.districtPopUp.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
self.visualEffectView.alpha = 1
}) { (success) in
self.districtPopUp.removeFromSuperview()
}
self.visualEffectView.isHidden = true
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
scrollView.setContentOffset(CGPoint(x: 0,y:-64), animated: true)
textField.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(CustomerViewController.hideKeyboard))
subView.addGestureRecognizer(tapGesture)
visualEffectView.isHidden = true
self.customerName.delegate = self
self.customerAddress.delegate = self
self.customerContact.delegate = self
self.customerIC.delegate = self
self.ticketNumber.delegate = self
self.latitudeGPS.delegate = self
self.longitudeGPS.delegate = self
self.district.delegate = self
// Do any additional setup after loading the view.
}
func hideKeyboard(){
scrollView.setContentOffset(CGPoint(x: 0,y:-64), animated: true)
self.customerName.resignFirstResponder()
self.customerAddress.resignFirstResponder()
self.customerContact.resignFirstResponder()
self.customerIC.resignFirstResponder()
self.ticketNumber.resignFirstResponder()
self.latitudeGPS.resignFirstResponder()
self.longitudeGPS.resignFirstResponder()
self.district.resignFirstResponder()
}
Instead of invoking resignFirstResponder() on each of your textFields you can just invoke view.endEditing(true) and keyboard will hide. Try to invoke this before the logic responsible for presenting the popup.
Simple and easy for all view controller swift 3+
This code help you to hide keyboard on touch anywhere on viewcontrol
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
}
Use below code in your viewDidLoad
self.hideKeyboardWhenTappedAround()

Swift 3 NavigationController segue back causes wkwebview to move into wrong position

I have a ViewController containing a WKWebView, the view is positioned correctly the first time it loads, but after moving to another view (I'm opening another view by intercepting links from the WebView) and pressing the navigation item (back button) it briefly appears in the right place, then reloads with the top of the webview behind the navigation bar so the top of the page is cut off.
class HomeVC: BaseViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView?
override func viewDidAppear(_ animated: Bool) {
self.edgesForExtendedLayout = UIRectEdge.top;
super.viewDidLoad()
addSlideMenuButton()
let screenSize: CGRect = UIScreen.main.bounds
let frameRect: CGRect = CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height)
let url: NSURL = Bundle.main.url(forResource: "services", withExtension: "html")! as NSURL
let requestObj: NSURLRequest = NSURLRequest(url: url as URL);
self.webView = WKWebView(frame: frameRect)
self.webView?.load(requestObj as URLRequest)
self.webView?.navigationDelegate = self
self.webView?.uiDelegate = self
self.view = self.webView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationItem.title = ""
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationItem.title = "SELECT A SERVICE"
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
let link: String = (webView.url?.absoluteString)!
print(link)
if(link == "file:///haircut") {
print(link)
self.openViewControllerBasedOnIdentifier("WebVC")
}
}
I've searched around and can't find any similar issues, nor can I see anything obvious in the code.
You have are calling super.viewDidLoad from func viewDidAppear(), what can cause unexpected behaviour. Therefore your UIViewController subclass will never notify its superclass, that the view has been loaded.
override func viewDidAppear(_ animated: Bool) {
// Do not do this before calling super!
self.edgesForExtendedLayout = UIRectEdge.top;
// You are calling the wrong the function for super
// It should be super.viewDidAppear(animated)
super.viewDidLoad()
addSlideMenuButton()
let screenSize: CGRect = UIScreen.main.bounds
let frameRect: CGRect = CGRect(x: 0, y: 100, width: screenSize.width, height: screenSize.height)
let url: NSURL = Bundle.main.url(forResource: "services", withExtension: "html")! as NSURL
let requestObj: NSURLRequest = NSURLRequest(url: url as URL);
self.webView = WKWebView(frame: frameRect)
self.webView?.load(requestObj as URLRequest)
self.webView?.navigationDelegate = self
self.webView?.uiDelegate = self
self.view = self.webView
}