iOS Revisited

Hot

Post Top Ad

Post Top Ad

27 Sept 2024

Exciting New Features in iOS 18: What You Need to Know

9/27/2024 07:07:00 am 0

Apple’s iOS 18 has arrived, bringing a host of new features designed to enhance user experience and make daily interactions with your device more intuitive and enjoyable. From interactive widgets to advanced messaging options, let’s dive into the most interesting features of iOS 18 that you won’t want to miss.

 


 

1. Interactive Widgets

One of the standout features in iOS 18 is the introduction of interactive widgets. Now, you can perform actions directly from your home screen without opening the respective apps. Whether it’s controlling music, checking off tasks, or viewing live data, these widgets make it easier than ever to stay organized and engaged with your favorite apps.

 

2. StandBy Mode

When you charge your iPhone horizontally, it activates StandBy Mode, transforming your device into a smart display. You can customize what is shown, including various clock styles, photos, or widgets. This feature is perfect for using your iPhone as a bedside clock or a mini dashboard when you need quick information at a glance.

 

3. Advanced Messaging Features

iOS 18 brings an array of improvements to the Messages app. You can now create and use stickers more easily, enhancing your conversations with a personal touch. The search functionality has also been revamped, making it simpler to find specific messages, photos, or links in your chat history.

 

4. New Journal App

Aiming to promote mindfulness, the new Journal app encourages users to reflect on their day. With built-in prompts and suggestions, you can easily jot down thoughts and experiences, helping you to maintain a record of your life and emotional well-being.

 

5. Enhanced Siri Functionality

Siri has become even more user-friendly in iOS 18. You can now make back-to-back requests without having to repeat “Hey Siri” each time, streamlining the interaction and making it feel more natural.

 

6. Safari Profiles

For those who like to keep work and personal browsing separate, Safari Profiles are a game-changer. You can create distinct profiles for different browsing needs, allowing you to manage tabs, bookmarks, and history independently. This feature enhances organization and privacy while surfing the web.

 

7. Health App Updates

The Health app has received significant upgrades, particularly in mental health tracking. Users can now log their mood and reflect on their emotional state, promoting awareness and encouraging users to maintain their mental well-being.

 

8. Improved Privacy Features

With increasing concerns about digital privacy, iOS 18 introduces enhanced privacy settings. Users now have more control over app permissions and tracking, allowing you to manage your data with confidence.

 

9. Visual Look Up Enhancements

Visual Look Up has been improved to support more types of content. Now, you can identify animals, landmarks, and even plants right from your photos, making it a handy tool for curious users.

 

10. FaceTime Updates

FaceTime gets a fun upgrade with new video effects and the ability to leave video messages for those who are unavailable. This feature allows for more engaging and personalized conversations, perfect for staying connected with friends and family.


Conclusion

iOS 18 is packed with features that enhance usability, personalization, and privacy. Whether you're looking to streamline your daily tasks or explore new ways to connect with others, this update has something for everyone. Dive into these exciting new features and make the most of your iPhone experience!

Read More

27 Apr 2020

Add button programmatically using Autolayouts Swift 5 - iOS

4/27/2020 03:37:00 am 0
Creating a button using autolayouts is quite simple. In this article, I will show how to add a button programmatically and in addition to that, we will learn about all attributes like color, font, image, etc..


Add button programatically using Autolayouts Swift 5 - iOS


Create UIButton:

First of all, create a new button object of type UIButton, and also set translatesAutoresizingMaskIntoConstraints to false. Then give the auto layouts as follow:

let swiftButton = UIButton()
swiftButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(swiftButton)
swiftButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20).isActive = true
swiftButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20).isActive = true
swiftButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
swiftButton.heightAnchor.constraint(equalToConstant: 50).isActive = true


Add a title to Button:

swiftButton.setTitle("Thunder", for: .normal)

Add a title to Button:

Change button title Font & Size:

swiftButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)


Change button title Font & Size:

Change Button background color:

swiftButton.backgroundColor = UIColor.white

Change Button background color:

Change Button title color:

swiftButton.setTitleColor(UIColor.black, for: .normal)

Change Button title color:

Add image to button:

swiftButton.setImage(UIImage(named: "thunder"), for: .normal)

Add image to button:

Change image color in Button:

swiftButton.tintColor = UIColor.red


 Change image color in Button:

Space between button image and title:


swiftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)

Space between button image and title:

Add tap action on Button:

swiftButton.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)



@objc func buttonTapped(sender: UIButton) {

    print("Button tapped")

}

Change Button title color On Tapped or Selected:

swiftButton.setTitleColor(UIColor.green, for: .highlighted)

Change Button title color On Tapped or Selected:
 

Conclusion:

As a result, we learn how to create a button programmatically & setting up all button properties.



Read More

21 Apr 2020

Dismiss multiple view controllers swift

4/21/2020 02:07:00 am 0
In order to dismiss more than one view controller, here is the small UIViewController extension that can work for many cases.

Cases like:

  • Dismiss to the particular view controller
  • Dismiss 2 or 3 or 4 or many view controllers (By count)
  • Dismiss to root view controller

Dismiss multiple view controllers swift

First of all, add this extension:

extension UIViewController {
    
    func dismissTo(vc: UIViewController?, count: Int?, animated: Bool, completion: (() -> Void)? = nil) {
        var loopCount = 0
        var dummyVC: UIViewController? = self
        for _ in 0..<(count ?? 100) {
            loopCount = loopCount + 1
            dummyVC = dummyVC?.presentingViewController
            if let dismissToVC = vc {
                if dummyVC != nil && dummyVC!.isKind(of: dismissToVC.classForCoder) {
                    dummyVC?.dismiss(animated: animated, completion: completion)
                }
            }
        }
        
        if count != nil {
            dummyVC?.dismiss(animated: animated, completion: completion)
        }
    }
    
}

Add this extension, and use it as follows...

Dismiss to particular view controller:

self.dismissTo(vc: SecondVC(), count: nil, animated: true)

Dismiss by count(1 to 100):

self.dismissTo(vc: nil, count: 3, animated: true)

Dismiss to root view controller:

self.dismissTo(vc: self.view.window?.rootViewController, count: nil, animated: true)

Finally, here is the sample project with four view controllers, download and check the example below.


Read More

16 Dec 2019

Create custom marker and custom info window in iOS using swift - Google maps

12/16/2019 09:29:00 am 10
In this article, we are going to learn about Custom Marker and Custom Info Window in Google maps.

First, create a new Xcode project and name it as Custom Marker.

In this example we are going to use completely auto layouts without a storyboard, every constraint is programmatically.

Download the sample project from the bottom of this tutorial.

Create custom marker and custom info window in iOS using swift - Google maps

Adding Google Map:

The first thing to do is integrate Google Maps SDK either using pod or other alternatives.

Here I am integrating using cocoapods.

Open terminal, go the project folder then type follow commands.

pod init

open -a xcode podfile

Then add pod 'GoogleMaps' below to the # Pods for CustomMarker.

pod install

After successful installation close the project and open workspace file.

To use google maps we need a key from google.

If you don't have one, get one from here

Okay, All set.

open AppDelegate.swift and import GoogleMaps then add the following line inside didFinishLaunchingWithOptions method:

GMSServices.provideAPIKey("YOUR API KEY")

open ViewController.swift and import GoogleMaps.

Add the following closure before viewDidLoad():

var mapView: GMSMapView = {
     let v = GMSMapView()
     v.translatesAutoresizingMaskIntoConstraints = false
     return v
 }()

Add mapView to the view as subview, add the following code inside viewDidLoad():

self.view.addSubview(mapView)
mapView.padding = UIEdgeInsets(top: 72, left: 25, bottom: 0, right: 25)
mapView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
mapView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
mapView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
mapView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
mapView.delegate = self

Don't panic with error, simply add the following extension to remove the error, we will discuss later in this example.

extension ViewController: GMSMapViewDelegate {
 
}

Now run the app, if your API key is valid you will see the map like below

Adding Google Map

Add Custom Marker:

Before creating a custom marker, first create our model, add the following model:

struct SSPlace {
    var name: String?
    var address: String?
    var coordinates: (lat: Double, lng: Double)?
}

Create array of SSPlaces as follow:

var places = [SSPlace]()

Add some sample data to places array, add the following code to the end of viewDidLoad():

places.append(SSPlace(name: "Fremont Troll", address: "N 36th St, Seattle, WA 98103, United States", coordinates: (lat: 47.651105, lng: -122.347347)))
places.append(SSPlace(name: "Grand Canyon National Park", address: "Arizona, United States", coordinates: (lat: 36.099982, lng: -112.123640)))
places.append(SSPlace(name: "Statue of Liberty National Monument", address: "New York, NY 10004, United States", coordinates: (lat: 40.689323, lng: -74.044490)))
places.append(SSPlace(name: "Yellowstone National Park", address: "United States", coordinates: (lat: 44.429311, lng: -110.588112)))
places.append(SSPlace(name: "Walt Disney World Resort", address: "Orlando, FL, United States", coordinates: (lat: 28.385280, lng: -81.563853)))

Now it's time to create a custom marker view.

Create a new swift file of type UIView and name it as CustomMarkerView. Replace the whole class with the following code:

class CustomMarkerView: UIView {
    
    var imageName: String?
    var borderColor: UIColor!
    
    init(frame: CGRect, imageName: String?, borderColor: UIColor, tag: Int) {
        super.init(frame: frame)
        self.imageName=imageName
        self.borderColor=borderColor
        self.tag = tag
        setupViews()
    }
    
    func setupViews() {
        let imgView = UIImageView()
        imgView.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(imgView)
        imgView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        imgView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        imgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        imgView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        imgView.layer.cornerRadius = 25
        imgView.layer.borderColor = borderColor?.cgColor
        imgView.contentMode = .scaleAspectFill
        imgView.layer.borderWidth = 4
        imgView.clipsToBounds = true
        imgView.image = UIImage(named: imageName!)
        
        let triangleImgView = UIImageView()
        self.insertSubview(triangleImgView, belowSubview: imgView)
        triangleImgView.translatesAutoresizingMaskIntoConstraints = false
        triangleImgView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
        triangleImgView.topAnchor.constraint(equalTo: imgView.bottomAnchor, constant: -6).isActive = true
        triangleImgView.widthAnchor.constraint(equalToConstant: 23/2).isActive = true
        triangleImgView.heightAnchor.constraint(equalToConstant: 24/2).isActive = true
        triangleImgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        triangleImgView.image = UIImage(named: "markerTriangle")
        triangleImgView.tintColor = borderColor
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

Here we are adding UIImageView to show the place image and one more UIImageView to show the bottom triangle.

Create new array to store all markers:

var markers = [GMSMarker]()

To add the places as markers on the map add the following method:

func addMarkers() {
    markers.removeAll()
    for (index, place) in places.enumerated() {
        let marker = GMSMarker()
        let customMarker = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: customMarkerWidth, height: customMarkerHeight), imageName: place.name, borderColor: primaryColor, tag: index)
        marker.iconView = customMarker
        marker.position = CLLocationCoordinate2D(latitude: place.coordinates!.lat, longitude: place.coordinates!.lng)
        marker.infoWindowAnchor = CGPoint(x: 0.5, y: 0)
        marker.map = self.mapView
        marker.zIndex = Int32(index)
        marker.userData = place
        markers.append(marker)
    }
}

Add the following colors before ViewController class:

let primaryColor = UIColor(red:0.00, green:0.19, blue:0.56, alpha:1.0)

let secondaryColor = UIColor(red:0.89, green:0.15, blue:0.21, alpha:1.0)

After adding markers to the map let focus them so that users can look at those places only.

To focus the markers add the following methods:

func focusMapToShowAllMarkers() {
    if let firstLocation = markers.first?.position {
        var bounds =  GMSCoordinateBounds(coordinate: firstLocation, coordinate: firstLocation)
        
        for marker in markers {
            bounds = bounds.includingCoordinate(marker.position)
        }
        let update = GMSCameraUpdate.fit(bounds, withPadding: 20)
        self.mapView.animate(with: update)
    }
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.focusMapToShowAllMarkers()
}

Finally call the addMarkers() function at the end of viewDidLoad():

override func viewDidLoad() {
       super.viewDidLoad()
       /***
       self.addMarkers()
}

That's it run the app, you can see markers as follows:

Create custom marke in iOS using swift - Google maps

Add Custom Info Window:

Create a new swift file of type UIView and name it as CustomMarkerInfoWindow. Replace the whole class with the following code:

class CustomMarkerInfoWindow: UIView {
    
    var txtLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var subtitleLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var chevronButton: UIButton = {
        let v = UIButton()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var imgView: UIImageView = {
        let v = UIImageView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = primaryColor
        self.addSubview(imgView)
        imgView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        imgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
        imgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
        imgView.widthAnchor.constraint(equalTo: imgView.heightAnchor, multiplier: 1).isActive = true
        imgView.heightAnchor.constraint(equalToConstant: 60).isActive = true
        imgView.clipsToBounds = true
        imgView.contentMode = .scaleAspectFill
        imgView.layer.cornerRadius = 5
        imgView.layer.masksToBounds = true
        imgView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]
        
        self.addSubview(chevronButton)
        chevronButton.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        chevronButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8).isActive = true
        chevronButton.widthAnchor.constraint(equalToConstant: 16).isActive = true
        chevronButton.heightAnchor.constraint(equalToConstant: 16).isActive = true
        chevronButton.setImage(UIImage(named: "chevron"), for: .normal)
        chevronButton.tintColor = UIColor.white
        chevronButton.isUserInteractionEnabled = false
        
        self.addSubview(txtLabel)
        txtLabel.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 4).isActive = true
        txtLabel.leadingAnchor.constraint(equalTo: imgView.trailingAnchor, constant: 8).isActive = true
        txtLabel.trailingAnchor.constraint(equalTo: chevronButton.leadingAnchor, constant: -8).isActive = true
        txtLabel.bottomAnchor.constraint(greaterThanOrEqualTo: centerYAnchor, constant: 2).isActive = true
        txtLabel.font = UIFont.boldSystemFont(ofSize: 16)
        txtLabel.numberOfLines = 2
        txtLabel.textColor = UIColor.white
        txtLabel.text = "dfsdfd"
        
        self.addSubview(subtitleLabel)
        subtitleLabel.topAnchor.constraint(equalTo: txtLabel.bottomAnchor, constant: 0).isActive = true
        subtitleLabel.leadingAnchor.constraint(equalTo: txtLabel.leadingAnchor).isActive = true
        subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        subtitleLabel.font = UIFont.systemFont(ofSize: 14, weight: .light)
        subtitleLabel.textColor = UIColor.white
        subtitleLabel.text = "55656556"
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        layer.masksToBounds = true
        layer.cornerRadius = 5
    }   
}

Code looks big but that's a simple auto layout.

Okay, now whenever user taps on the marker we need to change the border color to red and show info window.

First to change the selected marker color to red add the following delegate method to the extension:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    guard let customMarkerView = marker.iconView as? CustomMarkerView else { return false }
    let imgName = customMarkerView.imageName
    let customMarker = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: customMarkerWidth, height: customMarkerHeight), imageName: imgName, borderColor: secondaryColor, tag: customMarkerView.tag)
    marker.iconView = customMarker
    return false
}

Then to show the Marker info window add the following delegate method:

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
     if let place = marker.userData as? SSPlace {
         marker.tracksInfoWindowChanges = true
         let infoWindow = CustomMarkerInfoWindow()
         infoWindow.tag = 5555
         let height: CGFloat = 65
         let paddingWith = height + 16 + 32
         infoWindow.frame = CGRect(x: 0, y: 0, width: getEstimatedWidthForMarker(place, padding: paddingWith) + paddingWith, height: height)
         infoWindow.imgView.image = UIImage(named: place.name!)
         infoWindow.txtLabel.text = place.name
         infoWindow.subtitleLabel.text = place.address
         return infoWindow
     }
     return nil
 }
 
 func getEstimatedWidthForMarker(_ place: SSPlace, padding: CGFloat) -> CGFloat {
     var estimatedWidth: CGFloat = 0
     let infoWindow = CustomMarkerInfoWindow()
     let maxWidth = (UIDevice.current.userInterfaceIdiom == .pad ? UIScreen.main.bounds.width * 0.7 : UIScreen.main.bounds.width * 0.8) - padding
     let titleWidth = (place.name ?? "").width(withConstrainedHeight: infoWindow.txtLabel.frame.height, font: infoWindow.txtLabel.font)
     let subtitleWidth = (place.address ?? "").width(withConstrainedHeight: infoWindow.subtitleLabel.frame.height, font: infoWindow.subtitleLabel.font)
     estimatedWidth = min(maxWidth, max(titleWidth, subtitleWidth))
     return estimatedWidth
 }
 
 extension String {
     func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
         let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
         let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
         
         return ceil(boundingBox.width)
     }
 }

The getEstimatedWidthForMarker method is to calculate the window size based on the content.

Next after closing the info window you should change marker color is default blue, for that add the following delegate method:

func mapView(_ mapView: GMSMapView, didCloseInfoWindowOf marker: GMSMarker) {
    guard let customMarkerView = marker.iconView as? CustomMarkerView else { return }
    let imgName = customMarkerView.imageName
    let customMarker = CustomMarkerView(frame: CGRect(x: 0, y: 0, width: customMarkerWidth, height: customMarkerHeight), imageName: imgName, borderColor: primaryColor, tag: customMarkerView.tag)
    marker.iconView = customMarker
}

That's it all done, run the code you will see a map with markers then tap any one of the markers you will see the info window opened with marker color changed.

Create custom info window in iOS using swift - Google maps

This tutorial looks long, but you can directly download code or check in the Github.


Read More

11 Dec 2019

Chat App | Message Bubble in iOS Swift Without any external libraries.

12/11/2019 10:00:00 am 2
In this article we will learn how to create our own message kit like whatsapp, messanger using swift language.

We can customize the way we want like avatar, sender name, time label etc.


Chat App | Message Bubble in iOS Swift Without any external libraries.


At the end of this article you can find full project link.

Let's get started.

First create new single view application in xcode project.

Then add UITableView to the view and give constraints.

Create Custom UITableViewCell, this is important to create chat bubble.

Sender Chat Bubble:

Sender cell needs to have th message text and time.

The following method will do the magic.

func setupSendersCell() {
    let offset = UIEdgeInsets(top: padding, left: padding, bottom: -padding, right: -padding)
    self.contentView.addSubview(bgView)
    bgView.edges([.right, .top, .bottom], to: self.contentView, offset: offset)
    bgView.layer.cornerRadius = 8
    bgView.backgroundColor = UIColor(displayP3Red: 0, green: 122/255, blue: 255/255, alpha: 1)
    
    self.bgView.addSubview(textView)
    textView.edges([.left, .right, .top], to: self.bgView, offset: .init(top: innerSpacing, left: innerSpacing, bottom: -innerSpacing, right: -innerSpacing))
    bgView.leadingAnchor.constraint(greaterThanOrEqualTo: self.contentView.leadingAnchor, constant: extraSpacing).isActive = true
    textView.isScrollEnabled = false
    textView.isEditable = false
    textView.isSelectable = true
    textView.font = UIFont.systemFont(ofSize: 14)
    textView.textColor = UIColor.white
    textView.text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum"
    textView.backgroundColor = UIColor.clear
    
    self.bgView.addSubview(bottomLabel)
    bottomLabel.edges([.left, .bottom], to: self.bgView, offset: UIEdgeInsets(top: innerSpacing, left: secondaryPadding, bottom: -secondaryPadding, right: 0))
    bottomLabel.trailingAnchor.constraint(equalTo: textView.trailingAnchor, constant: -secondaryPadding).isActive = true
    bottomLabel.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: -2).isActive = true
    bottomLabel.font = UIFont.systemFont(ofSize: 10)
    bottomLabel.textColor = UIColor.white
    bottomLabel.textAlignment = .right
    bottomLabel.text = "12:00 AM"
}

Receiver Chat Bubble:

Receiver cell same as sender cell but it subviews should algin to leading where sender cell subviews align to trailing of superview.

The following method will do the magic.

func setupReceiversCell() {
    let offset = UIEdgeInsets(top: padding, left: padding, bottom: -padding, right: -padding)
    self.contentView.addSubview(bgView)
    bgView.edges([.left, .top, .bottom], to: self.contentView, offset: offset)
    bgView.layer.cornerRadius = 8
    bgView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
    
    self.bgView.addSubview(topLabel)
    topLabel.edges([.left, .top], to: self.bgView, offset: UIEdgeInsets(top: secondaryPadding, left: secondaryPadding, bottom: 0, right: 0))
    topLabel.font = UIFont.boldSystemFont(ofSize: 14)
    topLabel.textColor = UIColor.red
    topLabel.text = "Red"
    
    self.bgView.addSubview(textView)
    textviewTopConstraintToTopLabel = textView.topAnchor.constraint(equalTo: topLabel.bottomAnchor, constant: 0)
    textviewTopConstraintToTopLabel.isActive = true
    textviewTopConstraintToBg = textView.topAnchor.constraint(equalTo: bgView.topAnchor, constant: innerSpacing)
    textviewTopConstraintToBg.isActive = false
    textView.leadingAnchor.constraint(equalTo: bgView.leadingAnchor, constant: innerSpacing).isActive = true
    textView.trailingAnchor.constraint(equalTo: bgView.trailingAnchor, constant: -innerSpacing).isActive = true
    topLabel.trailingAnchor.constraint(lessThanOrEqualTo: textView.trailingAnchor, constant: 0).isActive = true
    bgView.trailingAnchor.constraint(lessThanOrEqualTo: self.contentView.trailingAnchor, constant: -extraSpacing).isActive = true
    textView.isScrollEnabled = false
    textView.isEditable = false
    textView.isSelectable = true
    textView.font = UIFont.systemFont(ofSize: 14)
    textView.text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum"
    textView.backgroundColor = UIColor.clear
    
    self.bgView.addSubview(bottomLabel)
    bottomLabel.edges([.left, .bottom], to: self.bgView, offset: UIEdgeInsets(top: innerSpacing, left: secondaryPadding, bottom: -secondaryPadding, right: 0))
    bottomLabel.trailingAnchor.constraint(equalTo: textView.trailingAnchor, constant: -secondaryPadding).isActive = true
    bottomLabel.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: -2).isActive = true
    bottomLabel.font = UIFont.systemFont(ofSize: 10)
    bottomLabel.textColor = UIColor.lightGray
    bottomLabel.textAlignment = .right
    bottomLabel.text = "12:00 AM"
}

Add the two cells to tableview and give some random messages.

Input TextView:

Adding texview is little bit tricky, here i created input textview like whatsapp.

The send button will show up when ever some text is there in textbox.

Finally project will looks like the following




Download sample project with example :

Read More

10 Dec 2019

Firebase Dynamic Link Not Found in swift ios

12/10/2019 04:50:00 am 0
Failed to resolve uri domain prefix: https://www.yourdomain.com.

If you are the developer of this app, ensure that your Dynamic Links domain is correctly configured and that the path component of this URL is valid.

If you are the developer of this app, ensure that your Dynamic Links domain is correctly configured and that the path component of this URL is valid.

Possible reasons for the invalid dynamic link error:

Reason 1:

First thing you need to check with apple-app-site-association as follow

paste your domain with apple-app-site-association https://www.yourdomain.com/apple-app-site-association.

Expected output should be

{"applinks":{"apps":[],"details":[{"appID":"LQABBB9F84.com.yourdomain.YourDomain","paths":["NOT /_/*","/*"]}]}}

Incase if you are getting `Dynamic Link Not Found` means check the following two things:

1. App Store ID is valid or not
2. Team ID should be same the one in provising profile

Reason 2:

Second possbile reason might be in capabilities.

Enable assocaited domains and add your domain as applinks:www.yourdomain.com.

Here make sure that you need to remove https://, otherwise deeplink url will not work as expected.

Reason 3:

If you are using any custom domains that means you are not using domains that ends with page.link, you need to add FirebaseDynamicLinksCustomDomains key in info.plist.

<key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://www.yourdomain.com/test1</string>
    <string>https://www.yourdomain.com/test2</string>
</array>


Not required if you are using domains with page.link.

Reason 4:

On some iOS devices it always goes to browser, but the same link will work on other ios devices. This is because of safari caching.

Go to settings in iOS device, then tap on safari and open reader, then tap on edit select preview.page.link and delete.

Go to settings in iOS device, then tap on safari and open reader, then tap on edit select preview.page.link and delete.

That's it should work fine.

Tip: You can try pasting the url in notes app and long press on the link then tap on `open in your app'

Read More

12 Aug 2019

Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

8/12/2019 10:39:00 am 1
Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

Adding image view to tab bar is quite easy.

First create new single view application. Embed ViewController inside tabBarController and add new tab name it my account.

After doing all above stuff you will see output as the following image


Embed ViewController inside tabBarController and add new tab name it my account.

Now drag some sample image to image assets and name it as profile.

Add the following extension to your project, you can add after the ViewController.swift class ends.

extension UITabBarController {
    
    func addSubviewToLastTabItem(_ imageName: String) {
        if let lastTabBarButton = self.tabBar.subviews.last, let tabItemImageView = lastTabBarButton.subviews.first {
            if let accountTabBarItem = self.tabBar.items?.last {
                accountTabBarItem.selectedImage = nil
                accountTabBarItem.image = nil
            }
            let imgView = UIImageView()
            imgView.frame = tabItemImageView.frame
            imgView.layer.cornerRadius = tabItemImageView.frame.height/2
            imgView.layer.masksToBounds = true
            imgView.contentMode = .scaleAspectFill
            imgView.clipsToBounds = true
            imgView.image = UIImage(named: imageName)
            self.tabBar.subviews.last?.addSubview(imgView)
        }
    }
}

Now open ViewController.swift file add the following method:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.tabBarController?.addSubviewToLastTabItem("profile")
}

That's it, Now run the app you will the desired results as follow:

Add ImageView (profile picture) to TabBar item (UITabBarController) using swift 5 - iOS

Read More

20 Jun 2019

Add View below TabBar Controller in swift - iOS

6/20/2019 11:21:00 am 0

In this post we are going to learn how to add a subview under UITabBarController in swift 5.

Add View below TabBar Controller in swift - iOS


First download the starter project from the below link:



Open the project and run, we will  see as  below images in the simulator.



Add View below TabBar Controller in swift - iOS


In this project we have Home View controller to display list of places, Detail view controller for place detail & Account view controller for second tab.

Let’s dive into the goal.

First create new swift file subclass of UIView, name it TabBarSwitchView.swift.

In this view we are going add switch. 


Replace TabBarSwitchView class with the following code:

import UIKit

class TabBarSwitchView: UIView {
    
    let onColor = UIColor(hex: 0xF9CF2D)
    
    let offColor = UIColor.white
    
    let deselectColor = UIColor(hex: 0xBFBFBF)
    
    let bgColor = UIColor(hex: 0x404040)
    
    var travellerLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var hostLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var switchButton: UISwitch = {
        let v = UISwitch()
        v.isUserInteractionEnabled = false
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var ison: Bool = false {
        didSet {
            isTraveller = !ison
            switchButton.setOn(ison, animated: true)
            if ison {
                hostLabel.textColor = onColor
                travellerLabel.textColor = deselectColor
            }else {
                hostLabel.textColor = deselectColor
                travellerLabel.textColor = offColor
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }
    
    let scale:CGFloat = 0.6
    
    func setupViews() {
        self.backgroundColor = bgColor
        self.addSubview(switchButton)
        switchButton.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
        switchButton.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
        switchButton.onTintColor = onColor
        switchButton.tintColor = UIColor.white
        switchButton.thumbTintColor = bgColor
        switchButton.layoutIfNeeded()
        switchButton.backgroundColor = offColor
        switchButton.layer.cornerRadius = 16
        switchButton.transform = CGAffineTransform(scaleX: scale, y: scale)
        
        self.addSubview(travellerLabel)
        travellerLabel.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
        travellerLabel.trailingAnchor.constraint(equalTo: switchButton.leadingAnchor, constant: -8).isActive = true
        travellerLabel.text = "TRAVELLER"
        travellerLabel.font = UIFont.systemFont(ofSize: 12)
        travellerLabel.textColor = UIColor.white
        
        self.addSubview(hostLabel)
        hostLabel.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
        hostLabel.leadingAnchor.constraint(equalTo: switchButton.trailingAnchor, constant: 8).isActive = true
        hostLabel.text = "HOST"
        hostLabel.font = UIFont.systemFont(ofSize: 12)
        hostLabel.textColor = onColor
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}


Next create new view controller and name it as TabBarRootVC.swift.

Replace code with following code:

import UIKit

var isTraveller = false
class TabBarRootVC: UIViewController {

    private lazy var tabBarVC: CustomTabBarVC = {
        var viewController = CustomTabBarVC()
        return viewController
    }()
    
    var bottomHeight: CGFloat {
        guard #available(iOS 11.0, *),
            let window = UIApplication.shared.keyWindow else {
                return 0
        }
        return window.safeAreaInsets.bottom
    }
    
    var switchView: TabBarSwitchView = {
        let v = TabBarSwitchView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var hideBottomBar: Bool = false {
        didSet {
            if hideBottomBar {
                heightConstraint.constant = 0
            }else {
                heightConstraint.constant = 32 + bottomHeight
            }
            UIView.animate(withDuration: 0.3) {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    var heightConstraint: NSLayoutConstraint!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }
    
    func setupViews() {
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(switchView)
        switchView.edges([.left, .right, .bottom], to: self.view, offset: .zero)
        heightConstraint = switchView.heightAnchor.constraint(equalToConstant: 32 + bottomHeight)
        heightConstraint.isActive = true
        switchView.ison = false
        switchView.isUserInteractionEnabled = true
        switchView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(switchViewTapped(recognizer:))))
        
        addChild(tabBarVC)
        self.view.addSubview(tabBarVC.view)
        tabBarVC.view.translatesAutoresizingMaskIntoConstraints = false
        tabBarVC.view.edges([.left, .right, .top], to: self.view, offset: .zero)
        tabBarVC.view.bottomAnchor.constraint(equalTo: switchView.topAnchor, constant: 0).isActive = true
        tabBarVC.didMove(toParent: self)
        if !hideBottomBar {
            heightConstraint.constant = 32 + bottomHeight
        }else {
            heightConstraint.constant = 0
        }
        
    }
    
    @objc func switchViewTapped(recognizer: UITapGestureRecognizer) {
        switchView.ison = !switchView.ison
        isTraveller = !switchView.ison
        NotificationCenter.default.post(name: Notification.Name(rawValue: "switchChanged"), object: nil)
    }
    

}

Open utilities file and add the following extension :

extension UIViewController {
    func hideBottomSwitch(_ hide: Bool) {
        if let customTab = self.tabBarController as? CustomTabBarVC {
            customTab.hideSwitch = hide
        }
    }
}


Open CustomTabBarVC.swift file and add the following code before viewDidLoad() :

var hideSwitch: Bool = false {
    didSet {
        print("view")
        if let parentVc = self.parent as? TabBarRootVC {
            parentVc.hideBottomBar = hideSwitch
        }
    }
}

Open the HomeViewController.swift file and replace all code with the following:


import UIKit

class HomeViewController: UIViewController {
    
    var tableView: UITableView = {
        let v = UITableView()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()
    
    var dataSource = [Place]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "Home"
        dataSource = [Place(name: "Ocean view during daylight", hostName: "Carey", imageName: "Ocean", createdOn: "23th Mar 2019"), Place(name: "Coconut palm trees", hostName: "Stark", imageName: "Trees", createdOn: "13th Mar 2019"), Place(name: "Trees in park", hostName: "Micheal", imageName: "Park", createdOn: "28th Feb 2019"), Place(name: "Water under sunset", hostName: "Shiny", imageName: "Sunset", createdOn: "16th Feb 2019"), Place(name: "Green trees beside roadway", hostName: "Nina", imageName: "Forest", createdOn: "1st Feb 2019")]
        setupViews()
        NotificationCenter.default.addObserver(self, selector: #selector(switchChanged), name:  Notification.Name(rawValue: "switchChanged"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.hideBottomSwitch(false)
    }
    
    func setupViews() {
        self.navigationController?.navigationBar.isTranslucent = false
        view.addSubview(tableView)
        tableView.edges([.all], to: view.safeAreaLayoutGuide, offset: .zero)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .singleLine
        tableView.separatorInset = .zero
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: CellIds.hostCellId)
        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: CellIds.travellerCellId)
    }
    
    @objc func switchChanged() {
        self.tableView.reloadData()
    }
}

extension HomeViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = DetailViewController()
        vc.place = dataSource[indexPath.row]
        vc.hidesBottomBarWhenPushed = true
        self.hideBottomSwitch(true)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension HomeViewController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if isTraveller {
            // Traveller Cell
            let cell = tableView.dequeueReusableCell(withIdentifier: CellIds.travellerCellId, for: indexPath) as! CustomTableViewCell
            let itemAtIndex = dataSource[indexPath.row]
            cell.imgView.image = UIImage(named: itemAtIndex.imageName)
            cell.txtLabel.text = itemAtIndex.name
            cell.subtitleLabel.text = itemAtIndex.hostName
            cell.selectionStyle = .none
            return cell
        }else {
            // Host Cell
            let cell = tableView.dequeueReusableCell(withIdentifier: CellIds.hostCellId, for: indexPath) as! CustomTableViewCell
            let itemAtIndex = dataSource[indexPath.row]
            cell.imgView.image = UIImage(named: itemAtIndex.imageName)
            cell.txtLabel.text = itemAtIndex.name
            cell.subtitleLabel.text = itemAtIndex.createdOn
            cell.selectionStyle = .none
            return cell
        }
    }
    
}


Now run the project we will see output as following:

Add View below TabBar Controller in swift - iOS


Download the finished project from the following link:


Read More

11 Jun 2019

Swift UISwitch color in On state & Off state, Change Switch height in swift - iOS

6/11/2019 10:48:00 am 0

UISwitch in swift has two states either On or Off. This switches mostly see in native  settings app.

Switch colors change in swift ios


First add switch to view as below, add following code in viewDidLoad() method:

let switchButton = UISwitch()
switchButton.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(switchButton)
switchButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0).isActive = true
switchButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0).isActive = true
switchButton.isOn = true

Run the code, you will see switch in On state with green color.

Tap on switch to turn off, color changes to white.

Green is for On, White is for Off these are default colors for switch in swift.

Now we will change default colors,

On - Blue 
Off - Red 

Add the following to the end of viewDidLoad() method:


// Colors
switchButton.onTintColor = UIColor.blue
switchButton.tintColor = UIColor.red
switchButton.thumbTintColor = UIColor.white
switchButton.backgroundColor = UIColor.red
switchButton.layer.cornerRadius = 16

Run the code you will see different colors unlike default color for switch in ios.

Change Switch Height:  

For changing the height of switch in swift we need to do following,  Add below code to the end of viewDidLoad():

// change height
switchButton.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)

Run code, we will switch button size with small size.






Read More

9 Jun 2019

Cannot preview in this file - active schema cannot build this file Xcode 11 beta.

6/09/2019 12:37:00 am 0
This is happening most of times, no need to worry we can fix with one of the following solutions.


Solution 1:

Go to Xcode preferences -> Locations -> Command line tools

Here, most of them are set to Xcode 10, change to Xcode 11.

Restart Xcode 11 beta, the try it should be ok.

Solution 2:

1. Delete the ContentView.swift file.

2. Create new 'SwiftUI View'

3. Name it same as ContentView.swift.

4. Now click resume in the canvas, we can see preview loading.

Sometimes restarting system may also help.
Read More

Post Top Ad