UICollectionView deselect all cell
1 2 3 4 5 6 7 |
extension UICollectionView { func deselectAllItems(animated: Bool) { guard let selectedItems = indexPathsForSelectedItems else { return } for indexPath in selectedItems { deselectItem(at: indexPath, animated: animated) } } } |
iOS: Swift location tracking
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
extension ViewController: CLLocationManagerDelegate { func determineMyCurrentLocation() { var locationManager: CLLocationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.startUpdatingLocation() //locationManager.startUpdatingHeading() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var userLocation: CLLocation = locations[0] as CLLocation // Call stopUpdatingLocation() to stop listening for location updates, // other wise this function will be called every time when user location changes. // manager.stopUpdatingLocation() // print("user latitude = \(userLocation?.coordinate.latitude)") // print("user longitude = \(userLocation?.coordinate.longitude)") } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error \(error)") } } |
Add into info.plist
1 2 3 4 5 |
<key>NSLocationAlwaysUsageDescription</key> <string>Will you allow this app to always know your location?</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Do you allow this app to know your current location?</string> |
iOS: Swift change color of placeholder in iOS 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
// // SSTextField.swift // // // Created by Shubham Sharma on 17/01/20. // Copyright © 2020 Shubham Sharma. All rights reserved. // import UIKit @IBDesignable @objc open class SSTextField: UITextField { /// Change placeholder color. @IBInspectable open var placeHolderColor : UIColor = UIColor.lightGray { didSet { self.initialize() } } // MARK:- Loading From NIB override open func awakeFromNib() { super.awakeFromNib() self.initialize() } // MARK:- Intialization override public init(frame: CGRect) { super.init(frame: frame) self.initialize() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initialize() } //MARK:- ACFLoating Initialzation. func initialize() -> Void { let iVar = class_getInstanceVariable(UITextField.self, "_placeholderLabel")! if let placeholderLabel = object_getIvar(self, iVar) as? UILabel { placeholderLabel.textColor = placeHolderColor } } } |
iOS: Swift basic Extensions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import Foundation import UIKit extension UIColor { static let AppDustyOrange:UIColor = UIColor(named: "AppDustyOrange")! static let AppDenimBlue:UIColor = UIColor(named: "AppDenimBlue")! static let AppBrownishGrey:UIColor = UIColor(named: "AppBrownishGrey")! } extension NSNotification.Name { static let UpdateUserProfile:NSNotification.Name = NSNotification.Name.init("UpdateUserProfile") static let UpdatePost:NSNotification.Name = NSNotification.Name.init("UpdatePost") static let UpdateCommentCount:NSNotification.Name = NSNotification.Name.init("UpdateCommentCount") static let RecevedPushNotification:NSNotification.Name = NSNotification.Name.init("RecevedPushNotification") } extension UIFont { static func appFont(size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont { switch weight { case UIFont.Weight.bold: return UIFont(name: "Roboto-Bold", size: size) ?? UIFont.systemFont(ofSize: size, weight: weight) case UIFont.Weight.light: return UIFont(name: "Roboto-Light", size: size) ?? UIFont.systemFont(ofSize: size, weight: weight) case UIFont.Weight.regular: return UIFont(name: "Roboto", size: size) ?? UIFont.systemFont(ofSize: size, weight: weight) default: return UIFont(name: "Roboto", size: size) ?? UIFont.systemFont(ofSize: size, weight: weight) } } } |
iOS: Swift listen JavaScript function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
// // WebViewScriptViewController.swift // UpgradeMySelf-ios // // Created by Shubham Sharma on 20/01/20. // Copyright © 2020 Shubham Sharma. All rights reserved. // import UIKit import WebKit class WebViewScriptViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var webView: WKWebView! private var webViewContentIsLoaded = false var __url: String = "https://www.google.com/" override func viewDidLoad() { super.viewDidLoad() webView.configuration.userContentController.add(self, name: "paymentResponse") webView.scrollView.bounces = false webView.navigationDelegate = self if !webViewContentIsLoaded { let url = URL(string: __url)! let request = URLRequest(url: url) webView.load(request) webViewContentIsLoaded = true } } private func evaluateJavascript(_ javascript: String, sourceURL: String? = nil, completion: ((_ error: String?) -> Void)? = nil) { var javascript = javascript // Adding a sourceURL comment makes the javascript source visible when debugging the simulator via Safari in Mac OS if let sourceURL = sourceURL { javascript = "//# sourceURL=\(sourceURL).js\n" + javascript } webView.evaluateJavaScript(javascript) { _, error in completion?(error?.localizedDescription) } } // MARK: - WKNavigationDelegate func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { // This must be valid javascript! Critically don't forget to terminate statements with either a newline or semicolon! let javascript = "var message = {\"Status\": \"SUCCESS\", \"transactionId\": \"#PAY123133\" }\n" + "window.webkit.messageHandlers.paymentResponse.postMessage(message)\n" evaluateJavascript(javascript, sourceURL: nil) } func showAlertWithMessage(title: String, message:String ) { let alert = UIAlertController.init(title: title , message:message , preferredStyle:.alert) let action = UIAlertAction.init(title: "OK", style: .cancel) { (action) in } alert.addAction(action) self.present(alert, animated:true, completion: nil) } } extension WebViewScriptViewController: WKScriptMessageHandler { // MARK: - WKScriptMessageHandler func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.body) guard let body = message.body as? [String: Any] else { print("could not convert message body to dictionary: \(message.body)") showAlertWithMessage(title: "Payment Declined", message: "" ) return } guard let status = body["Status"] as? String else { print("could not convert Status to string: \(body)") showAlertWithMessage(title: "Payment Declined", message: "" ) return } switch status { case "FAILED": showAlertWithMessage(title: "Payment Declined", message: "") print("Transaction Failed") break case "SUCCESS": guard let transactionId = body["transactionId"] as? String else { print("could not transactionId to string: \(body)") return } print("outerHTML is \(transactionId)") showAlertWithMessage(title: "Payment Declined", message: "Transaction Id \(transactionId)" ) break default: print("unknown message type \(status)") return } } } |
Swift: Add attributed string in iOS
1 2 3 4 5 6 7 8 9 10 |
let attributsBold = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13.0, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.AppPrimaryColor] let attributsNormal = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13.0, weight: .regular), NSAttributedString.Key.foregroundColor: UIColor.AppSlate] let attributedString = NSMutableAttributedString(string: "Bold Text", attributes:attributsBold) let boldStringPart = NSMutableAttributedString(string: "Regular Text", attributes:attributsNormal) attributedString.append(boldStringPart) UITextViewObject.attributedText = attributedString |
Swift Date format refrence
Characters Example Description Year y 2008 Year, no padding yy 08 Year, two digits (padding with a zero if necessary) yyyy 2008 Year, minimum of four digits (padding with zeros if necessary) Quarter Q 4 The quarter of the year. Use QQ if you want zero padding. QQQ Q4 Quarter including “Q” QQQQ 4th quarter […]
iOS Date picker view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
import UIKit class ViewController: UIViewController { @IBOutlet weak var textField: UITextField! fileprivate var tmpSelectedDate:String = "" override func viewDidLoad() { super.viewDidLoad() pickerViewInit() // Do any additional setup after loading the view. } } extension ViewController { //MARK:pickerView //***************************************************** func pickerViewInit(){ //Create a parent view for UIPickerView let pickerViewWrpper = UIView(frame: CGRect(x:0, y: 200, width: self.view.bounds.width, height: 200)) pickerViewWrpper.backgroundColor = .clear //create UIPickerView object let datepicker = UIDatePicker( ) datepicker.backgroundColor = .clear //add UIPickerView into parent view pickerViewWrpper.addSubview(datepicker) datepicker.datePickerMode = UIDatePicker.Mode.date //add some constraint to UIPickerView datepicker.translatesAutoresizingMaskIntoConstraints = false datepicker.leadingAnchor.constraint(equalTo: pickerViewWrpper.leadingAnchor, constant: 0).isActive = true datepicker.trailingAnchor.constraint(equalTo: pickerViewWrpper.trailingAnchor, constant: 0).isActive = true datepicker.bottomAnchor.constraint(equalTo: pickerViewWrpper.bottomAnchor, constant: 0).isActive = true datepicker.heightAnchor.constraint(equalToConstant: 170).isActive = true datepicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged) //set data source and other stuff //create UIToolbar object let toolBar = UIToolbar() //add UIToolbar into parent view pickerViewWrpper.addSubview(toolBar) //add some constraint to UIToolbar toolBar.translatesAutoresizingMaskIntoConstraints = false toolBar.leadingAnchor.constraint(equalTo: pickerViewWrpper.leadingAnchor, constant: 0).isActive = true toolBar.trailingAnchor.constraint(equalTo: pickerViewWrpper.trailingAnchor, constant: 0).isActive = true toolBar.topAnchor.constraint(equalTo: pickerViewWrpper.topAnchor, constant: 0).isActive = true toolBar.heightAnchor.constraint(equalToConstant: 30).isActive = true //add some style to UIToolbar toolBar.barStyle = UIBarStyle.default toolBar.isTranslucent = true // toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1) toolBar.sizeToFit() //int done and cancelButton buttons let doneButton = UIBarButtonItem(title: "Select", style: UIBarButtonItem.Style.plain, target: self, action: #selector(donePicker)) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancelPicker)) toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true //set inputView when we enter in text field this view will show insted of keyboard textField.inputView = pickerViewWrpper } @objc func donePicker(){ textField.resignFirstResponder() textField.text = tmpSelectedDate } @objc func cancelPicker(){ textField.resignFirstResponder() } @objc func dateChanged(_ sender: UIDatePicker) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" tmpSelectedDate = dateFormatter.string(from: sender.date) //Uncomment if user wants to update text field date same time when user change date // childDOB.text = dateFormatter.string(from: sender.date) } //***************************************************** //End pickerView } |