How to create a tab bar using SingleViewApplication iOS? - ios

I am new in iOS and my requirement is to implement Tab bar.
I have 5 tab bar items and for each item there is different Screen(UIViewController).
I have a HomeViewController and remaining 4 ViewControllers.
I have to show all UIViewControllers using tabBar item.
And I have to show tab bar in bottom for all UIViewControllers.
In Image You can see.
In Image, I am in HomeViewController and for each tab I have to go for respective ViewControllers but tab bar should be present for all ViewControllers.
StoryBoard :-
I read tutorials but still confused.
How can I do it?
Thanks

You can create the class of tab view controller like this
class TabBarViewController: UITabBarController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = UIColor(red: 254/255.0, green: 105/255.0, blue: 51/255.0, alpha: 100.0)
for i in 0 ..< self.tabBar.items!.count {
switch i {
case 0:
tabBar.items?[0].title = "Home"
let firstTab = self.tabBar.items![i] as UITabBarItem
learnTab.image = UIImage(named: "Homedeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
firstTab.selectedImage = UIImage(named: "Homedeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
firstTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
firstTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 1:
tabBar.items?[1].title = "Request"
let secondTab = self.tabBar.items![i] as UITabBarItem
secondTab.image = UIImage(named: "RequestDeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
secondTab.selectedImage = UIImage(named: "Requestselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
secondTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
secondTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 2:
tabBar.items?[2].title = "Renew"
let thirdTab = self.tabBar.items![i] as UITabBarItem
thirdTab.image = UIImage(named: "RenewDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
thirdTab.selectedImage = UIImage(named: "RenewSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
thirdTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
thirdTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 3:
tabBar.items?[3].title = "ReSell"
let forthTab = self.tabBar.items![i] as UITabBarItem
forthTab.image = UIImage(named: "ReSellDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
forthTab.selectedImage = UIImage(named: "ReSellSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
forthTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
forthTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 4:
tabBar.items?[4].title = "ReCycle"
let fifthTab = self.tabBar.items![i] as UITabBarItem
fifthTab.image = UIImage(named: "ReCycleDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
fifthTab.selectedImage = UIImage(named: "ReCycleSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
fifthTab.imageInsets = UIEdgeInsetsMake(-2, 0, 2, 0)
fifthTab.titlePositionAdjustment = UIOffsetMake(0, -5)
default:
break
}
}
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
let rootView = self.viewControllers![self.selectedIndex] as! UINavigationController
rootView.popToRootViewControllerAnimated(ture)
}
}
}

Related

UINavigationBar Large Title doesn't appear when scroll view up

I have implemented a feature, when you press on a UITabBar icon and viewController1 scrolls up using its UIScrollView. It works perfectly, but if I scroll view down and stop somewhere, then switch to another viewController2, then get back to viewController1 and press tabBar icon - the viewController1 will scroll up, but Large Title will never be showed, and I should press tabBar icon one more time to show it:
The code I use for scroll up the VC1:
private var biggestTopSafeAreaInset: CGFloat = 0
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
self.biggestTopSafeAreaInset = max(view.safeAreaInsets.top, biggestTopSafeAreaInset)
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.selectedIndex == 0 {
let navigationVC = viewController as? UINavigationController
let firstVC = navigationVC?.viewControllers.first as? CurrencyViewController
guard let scrollView = firstVC?.view.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView else { return }
if traitCollection.verticalSizeClass == .compact {
scrollView.setContentOffset(CGPoint(x: 0, y: -view.safeAreaInsets.top, animated: true)
} else {
scrollView.setContentOffset(CGPoint(x: 0, y: -biggestTopSafeAreaInset, animated: true)
}
}
}
I tried to track biggestTopSafeAreaInset in different stages of VC1 life, but it always has the same number - 196.0. But then why it doesn't scroll till the Large Title after viewControllers switch?
in your tableView set contentInsetAdjustmentBehavior to never
tableView.contentInsetAdjustmentBehavior = .never
in controller update the ui of navigation bar again
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.main.async { [weak self] in
self?.navigationController?.navigationBar.sizeToFit()
}
}
here is the navigation controller
class BaseNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 15.0, *) {
let scrollAppearance = UINavigationBarAppearance()
scrollAppearance.shadowColor = .white
scrollAppearance.backgroundColor = .white
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.configureWithDefaultBackground()
navigationBarAppearance.backgroundColor = .white
navigationBarAppearance.largeTitleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBarAppearance.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.foregroundColor: UIColor.black
]
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "back-arrow")
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
UINavigationBar.appearance().compactAppearance = navigationBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = scrollAppearance
navigationBar.tintColor = .black
navigationBar.prefersLargeTitles = true
navigationBar.isTranslucent = false
navigationItem.largeTitleDisplayMode = .automatic
} else {
navigationBar.largeTitleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 26),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBar.titleTextAttributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.foregroundColor: UIColor.black
]
navigationBar.tintColor = .black
navigationBar.prefersLargeTitles = true
navigationBar.isTranslucent = false
navigationItem.largeTitleDisplayMode = .automatic
navigationBar.barTintColor = .white
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .darkContent
}
}
here is the Tabbar Controller
class TabbarController:UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let c1 = C1()
let c2 = C2()
let c3 = C3()
c1.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "home786"), tag: 0)
c1.tabBarItem.tag = 0
let nav1 = BaseNavigationController(rootViewController: c1)
c2.tabBarItem = UITabBarItem(title: "Setting", image: UIImage(named: "home786"), tag: 0)
c2.tabBarItem.tag = 1
let nav2 = BaseNavigationController(rootViewController: c2)
c2.tabBarItem = UITabBarItem(title: "User", image: UIImage(named: "home786"), tag: 0)
c2.tabBarItem.tag = 2
let nav3 = BaseNavigationController(rootViewController: c3)
viewControllers = [nav1,nav2,nav3]
selectedViewController = nav1
tabBarController?.viewControllers?.first?.view.backgroundColor = .red
}
}
Try to add this in viewDidLoad:
view.addSubview(UIView())
this single line block large title navigation Bar... I don't Know why, but this trick fix momentarily the issue...
After some research I found out what can fix my problem. If you call this method with a small delay in tabBarController didSelect then it will be possible to see a Large Title after switching viewControllers. But I still can't figure out exactly why it happened...
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
navigationVC?.navigationBar.sizeToFit()
}

NavigationItem titleView is coming at left side for some time then move to Center

I am setting a custom view as titleView of the navigation. When viewcontroller appear its title view comes at left side for a moment and then move to center,what could be wrong? I am using the following code
let itemImgs: [UIImage] = [UIImage(named: "MORE_Location")!, UIImage(named: "MORE_Department")!, UIImage(named: "By_Teams")!, UIImage(named: "MORE_Status")!]
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
menuView = BTNavigationDropdownMenu(navigationController: self.navigationController, containerView: self.navigationController!.view, title: AppMessage.EDEmployeePeople, items: items as [AnyObject], itemImgs: itemImgs)
menuView.cellHeight = 60
menuView.cellBackgroundColor = UIColor.red
menuView.cellSelectionColor = UIColor.clear
menuView.cellSeparatorColor = UIColor.clear
menuView.shouldKeepSelectedCellColor = false
menuView.cellTextLabelColor = UIColor.white
menuView.shouldChangeTitleText = false
menuView.cellTextLabelFont = UIFont(name: "Helvetica", size: 17)
if appNeedsAutoResize
{
menuView.cellTextLabelFont = UIUtils.getFontForApproprieteField(.subHeadline).font
}
menuView.cellTextLabelAlignment = .left // .Center // .Right // .Left
menuView.arrowPadding = 15
menuView.animationDuration = 0.5
menuView.maskBackgroundColor = UIColor.clear
menuView.maskBackgroundOpacity = 0.3
menuView.didSelectItemAtIndexHandler = {(indexPath: Int) -> () in
print("Did select item at index: \(indexPath)")
if indexPath == 3
{
let byStatusViewController = ByStatusViewController(nibName: "ByStatusViewController", bundle: nil)
//UIUtils.pushViewWhenHideBottom(self, anotherVC: byStatusViewController)
self.navigationController?.pushViewController(byStatusViewController, animated: true)
}
else
{
let dropVC = DepartmentViewController(nibName: "DepartmentViewController", bundle: nil)
switch indexPath
{
case 0:
dropVC.employeeGroupInfo = EmployeeGroupInfo.locationInfo
break
case 1:
dropVC.employeeGroupInfo = EmployeeGroupInfo.departmentInfo
break
default:
dropVC.employeeGroupInfo = EmployeeGroupInfo.teamInfo
break
}
// UIUtils.pushViewWhenHideBottom(self, anotherVC: dropVC)
self.navigationController?.pushViewController(dropVC, animated: true)
}
}
self.navigationItem.titleView = menuView
}
Try to add constraints of autoresizing masks to your menu view to keep the view centered.
E.g.
menuView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin]
I had this problem and changing my function that customize my navigationItem from viewWillAppear() to viewDidLoad() resolved

how to customize tabbar items which is added on storyboard

I made UITabbar controller and make 5 tabbar buttons on Storyboard.
But I cannot control image sizes and colors in tabbar items.
And I want to customize button colors and shapes using PNG files, not using default colors.
But the below code is not working at well except tabbar tintcolor.
class MainView: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
tabBar.barTintColor = UIColor.white
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
switch item.tag{
case 0:
print(item.tag)
UITabBar.setItems(item[0]) = UITabBarItem(title: "Magzine", image: UIImage(named: "exhibiter.png"), selectedImage: UIImage(named: "exhibiterselected.png"))
case 1:
print("")
case 2:
print("")
case 3:
print("")
case 4:
print("")
default:
break
}
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.isStatusBarHidden = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
you can use like this
class TabBarViewController: UITabBarController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = UIColor(red: 254/255.0, green: 105/255.0, blue: 51/255.0, alpha: 100.0)
for i in 0 ..< self.tabBar.items!.count {
switch i {
case 0:
tabBar.items?[0].title = "Home"
let firstTab = self.tabBar.items![i] as UITabBarItem
learnTab.image = UIImage(named: "Homedeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
firstTab.selectedImage = UIImage(named: "Homedeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
firstTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
firstTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 1:
tabBar.items?[1].title = "Request"
let secondTab = self.tabBar.items![i] as UITabBarItem
secondTab.image = UIImage(named: "RequestDeselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
secondTab.selectedImage = UIImage(named: "Requestselected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
secondTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
secondTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 2:
tabBar.items?[2].title = "Renew"
let thirdTab = self.tabBar.items![i] as UITabBarItem
thirdTab.image = UIImage(named: "RenewDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
thirdTab.selectedImage = UIImage(named: "RenewSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
thirdTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
thirdTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 3:
tabBar.items?[3].title = "ReSell"
let forthTab = self.tabBar.items![i] as UITabBarItem
forthTab.image = UIImage(named: "ReSellDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
forthTab.selectedImage = UIImage(named: "ReSellSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
forthTab.imageInsets = UIEdgeInsetsMake(-1, 0, 1, 0)
forthTab.titlePositionAdjustment = UIOffsetMake(0, -4)
case 4:
tabBar.items?[4].title = "ReCycle"
let fifthTab = self.tabBar.items![i] as UITabBarItem
fifthTab.image = UIImage(named: "ReCycleDeSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
fifthTab.selectedImage = UIImage(named: "ReCycleSelected")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
fifthTab.imageInsets = UIEdgeInsetsMake(-2, 0, 2, 0)
fifthTab.titlePositionAdjustment = UIOffsetMake(0, -5)
default:
break
}
}
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
}
}

How to set image in a tab bar item in Swift?

I have taken a view controller & embedded it in a navigation Controller and again this has been embedded in a tab bar controller. when I am trying to set a image via story board, the image does not appear on a tab bar icon. Here image name is 25.
What can I do? How can I do it programmatically? what should I take proper image size for this purpose?
In your MainTabbarViewController
Bind the outlet of your tabbar:
#IBOutlet weak var myTabBar: UITabBar?
override func viewDidLoad() {
super.viewDidLoad()
myTabBar?.tintColor = UIColor.white
tabBarItem.title = ""
setTabBarItems()
}
set the tabbar items here defined method below:
func setTabBarItems(){
let myTabBarItem1 = (self.tabBar.items?[0])! as UITabBarItem
myTabBarItem1.image = UIImage(named: "Unselected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem1.selectedImage = UIImage(named: "Selected ")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem1.title = ""
myTabBarItem1.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
let myTabBarItem2 = (self.tabBar.items?[1])! as UITabBarItem
myTabBarItem2.image = UIImage(named: "Unselected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem2.selectedImage = UIImage(named: "Selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem2.title = ""
myTabBarItem2.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
let myTabBarItem3 = (self.tabBar.items?[2])! as UITabBarItem
myTabBarItem3.image = UIImage(named: "Unselected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem3.selectedImage = UIImage(named: "Selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem3.title = ""
myTabBarItem3.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
let myTabBarItem4 = (self.tabBar.items?[3])! as UITabBarItem
myTabBarItem4.image = UIImage(named: "Unselected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem4.selectedImage = UIImage(named: "Selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
myTabBarItem4.title = ""
myTabBarItem4.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
}
add AppDelegate class :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
{
window=UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = setTabbar()
self.window?.makeKeyAndVisible()
window?.backgroundColor=UIColor.white
return true
}
func setTabbar() -> UITabBarController
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tabbarcntrl = UITabBarController()
let Home = storyboard.instantiateViewController(withIdentifier: "HomeView") // 1st tab bar viewcontroller
let Followed = storyboard.instantiateViewController(withIdentifier: "FollowedView") // 2nd tab bar viewcontroller
let Message = storyboard.instantiateViewController(withIdentifier: "MessageView") // 3rd tab bar viewcontroller
// all viewcontroller embedded navigationbar
let nvHome = UINavigationController(rootViewController: Home)
let nvFollowed = UINavigationController(rootViewController: Followed)
let nvMessage = UINavigationController(rootViewController: Message)
// all viewcontroller navigationbar hidden
nvHome.setNavigationBarHidden(true, animated: false)
nvFollowed.setNavigationBarHidden(true, animated: false)
nvMessage.setNavigationBarHidden(true, animated: false)
tabbarcntrl.viewControllers = [nvHome,nvFollowed,nvMessage]
let tabbar = tabbarcntrl.tabBar
tabbar.barTintColor = UIColor.black
tabbar.backgroundColor = UIColor.black
tabbar.tintColor = UIColor(red: 43/255, green: 180/255, blue: 0/255, alpha: 1)
//UITabBar.appearance().tintColor = UIColor.white
let attributes = [NSFontAttributeName:UIFont(name: "Montserrat-Light", size: 10)!,NSForegroundColorAttributeName:UIColor.white]
let attributes1 = [NSFontAttributeName:UIFont(name: "Montserrat-Light", size: 10)!,NSForegroundColorAttributeName:UIColor(red: 43/255, green: 180/255, blue: 0/255, alpha: 1)]
UITabBarItem.appearance().setTitleTextAttributes(attributes, for: .normal)
UITabBarItem.appearance().setTitleTextAttributes(attributes1, for: .selected)
let tabHome = tabbar.items![0]
tabHome.title = "Home" // tabbar titlee
tabHome.image=UIImage(named: "icon_home.png")?.withRenderingMode(.alwaysOriginal) // deselect image
tabHome.selectedImage = UIImage(named: "icon_home.png")?.withRenderingMode(.alwaysOriginal) // select image
tabHome.titlePositionAdjustment.vertical = tabHome.titlePositionAdjustment.vertical-4 // title position change
let tabFoll = tabbar.items![1]
tabFoll.title = "Followed"
tabFoll.image=UIImage(named: "icon_fold.png")?.withRenderingMode(.alwaysOriginal)
tabFoll.selectedImage=UIImage(named: "icon_fold.png")?.withRenderingMode(.alwaysOriginal)
tabFoll.titlePositionAdjustment.vertical = tabFoll.titlePositionAdjustment.vertical-4
let tabMsg = tabbar.items![3]
tabMsg.title = "Message"
tabMsg.image=UIImage(named: "icon_mail.png")?.withRenderingMode(.alwaysOriginal)
tabMsg.selectedImage=UIImage(named: "icon_mail.png")?.withRenderingMode(.alwaysOriginal)
tabMsg.titlePositionAdjustment.vertical = tabMsg.titlePositionAdjustment.vertical-4
return tabbarcntrl
}
Set both images- for select/selected state
You are doing all the things in right way But the only problem is your tabbaritem image is not in correct size .Just look this table for actual size of tabbaritem images.
In swift 4 and 5 you can use the below extension. Remember one thing always pass the same number of images , selected images and title but if you do not want to set title then pass nil in title.
extension UITabBarController{
func setUpImagaOntabbar(_ selectedImage : [UIImage], _ image : [UIImage], _ title : [String]?){
for (index,vals) in image.enumerated(){
if let tab = self.tabBar.items?[index]{
tab.image = image[index]
tab.image = selectedImage[index]
if let tile = title[index]{
tab.title = title[index]
}
}
}
}
}

Create a Utility function for UIActivityIndicator to show and hide depending on the condition in controller

Hello I have created a swift file in which I wrote some utility functions which I used in multiple controllers. I also wrote function for UIActivityIndicator. But somehow its not working as expected.
Here is my function
static func showIndicatorView(backgroundView: UIView,controller: UIViewController)->UIActivityIndicatorView{
let loadingIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
let backgroundView = UIView()
backgroundView.layer.cornerRadius = 05
backgroundView.clipsToBounds = true
backgroundView.opaque = false
backgroundView.backgroundColor = UIColor(white: 0.0, alpha: 0.6)
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loadingIndicator.color = UIColor.whiteColor()
loadingIndicator.startAnimating()
let loadingLabel = UILabel()
loadingLabel.text = "Loading..."
loadingLabel.textColor = UIColor.whiteColor()
let textSize: CGSize = loadingLabel.text!.sizeWithAttributes([NSFontAttributeName: loadingLabel.font ])
loadingLabel.frame = CGRectMake(50, 0, textSize.width, textSize.height)
loadingLabel.center.y = loadingIndicator.center.y
backgroundView.frame = CGRectMake(0, 0, textSize.width + 70, 50)
backgroundView.center = controller.view.center;
controller.view.addSubview(backgroundView)
backgroundView.addSubview(loadingIndicator)
backgroundView.addSubview(loadingLabel)
return loadingIndicator
}
I am doing this in controllers in order to show and hide the indicator
show
Utility.showIndicatorView(backgroundView, controller: self).startAnimating()
hide
Utility.showIndicatorView(backgroundView, controller: self).startAnimating()
Sometimes UiIndicatorView background doesn't remove from the controller. Please check my code and let me know how can I show and hide the uiindicator in one or two lines
Create a class for your loading view and add functions to show and hide the view like this:
import UIKit
class LoadingView: UIView {
override init (frame : CGRect) {
super.init(frame : frame)
let loadingIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
let backgroundView = UIView()
backgroundView.layer.cornerRadius = 05
backgroundView.clipsToBounds = true
backgroundView.opaque = false
backgroundView.backgroundColor = UIColor(white: 0.0, alpha: 0.6)
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
loadingIndicator.color = UIColor.whiteColor()
loadingIndicator.startAnimating()
let loadingLabel = UILabel()
loadingLabel.text = "Loading..."
loadingLabel.textColor = UIColor.whiteColor()
let textSize: CGSize = loadingLabel.text!.sizeWithAttributes([NSFontAttributeName: loadingLabel.font ])
loadingLabel.frame = CGRectMake(50, 0, textSize.width, textSize.height)
loadingLabel.center.y = loadingIndicator.center.y
backgroundView.frame = CGRectMake(0, 0, textSize.width + 70, 50)
backgroundView.center = self.center;
self.addSubview(backgroundView)
backgroundView.addSubview(loadingIndicator)
backgroundView.addSubview(loadingLabel)
}
convenience init () {
self.init(frame:UIScreen.mainScreen().bounds)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showLoadingView() {
if let rootViewController = UIApplication.topViewController() {
rootViewController.view.addSubview(self)
self.bringSubviewToFront(rootViewController.view)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
}
}
func hideLoadingView() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.removeFromSuperview()
}
}
// Get the visible ViewController
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController where top.view.window != nil {
return topViewController(top)
} else if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
}
Then init your loading view in your ViewController.
let lv = LoadingView()
lv.showLoadingView()
lv.hideLoadingView()

Resources