how to customize tabbar items which is added on storyboard - ios

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) {
}
}

Related

UITabBarController is not fitted to the screen in iOS Swift?

I have been implemented UITabBarController programmatically. Functionality works fine but the UITabBarController is not fitting inside the screen.
here is my code:
class ViewController: UIViewController {
let tabBarCnt = UITabBarController()
override func viewDidLoad() {
super.viewDidLoad()
tabBarCnt.tabBar.tintColor = UIColor.black
createTabBarController()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
addHeightConstraintToTabbar()
}
func addHeightConstraintToTabbar() -> Void {
let heightConstant:CGFloat = self.view.safeAreaInsets.bottom + 49.0
tabBarCnt.tabBar.heightAnchor.constraint(equalToConstant: heightConstant).isActive = true
}
func createTabBarController() {
let firstVc = UIViewController()
firstVc.title = "First"
firstVc.view.backgroundColor = UIColor.red
firstVc.tabBarItem = UITabBarItem.init(title: "Home", image: UIImage(named: "HomeTab"), tag: 0)
let secondVc = UIViewController()
secondVc.title = "Second"
secondVc.view.backgroundColor = UIColor.green
secondVc.tabBarItem = UITabBarItem.init(title: "Location", image: UIImage(named: "Location"), tag: 1)
let controllerArray = [firstVc, secondVc]
tabBarCnt.viewControllers = controllerArray.map{ UINavigationController.init(rootViewController: $0)}
self.view.addSubview(tabBarCnt.view)
}
}
Result screenshot
Add this line:
tabBarCnt.additionalSafeAreaInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

navigation bar back ground color will change into wrong color when table view scrolls in swift 4

I seen this video on you tube
https://www.youtube.com/watch?v=rNy6aQQYbuY
But the problem is that navigation bar color will not change color into correct color that I want to be
so here is the codes
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.tintColor = .white
if #available(iOS 11.0, *) {
self.profileTV.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
print(scrollView.contentOffset.y)
var offset = scrollView.contentOffset.y / 150
if offset > 1 {
offset = 1
let color = UIColor(red: 181, green: 40, blue: 56, alpha: offset)
self.navigationController?.navigationBar.backgroundColor = color
UIApplication.shared.statusBarView?.backgroundColor = color
} else {
let color = UIColor(red: 181, green: 40, blue: 56, alpha: offset)
self.navigationController?.navigationBar.backgroundColor = color
UIApplication.shared.statusBarView?.backgroundColor = color
}
}
extension UIApplication {
var statusBarView: UIView? {
return value(forKey: "statusBar") as? UIView
}
}
the color after scrolling will be white But I want to be the color code that I wrote in my codes
change your code to:
func setNavigation() {
if #available(iOS 11.0, *) {
self.tV.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
self.navigationController?.navigationBar.tintColor = .red
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var offset = scrollView.contentOffset.y / 1500
if offset >= 1 {
offset = 1
self.navigationController?.navigationBar.backgroundColor = UIColor.white.withAlphaComponent(offset)
// self.navigationController?.navigationBar.alpha = offset
// print(offset - 0.399)
UIApplication.shared.statusBarView?.backgroundColor = UIColor.red.withAlphaComponent(offset)
} else {
self.navigationController?.navigationBar.backgroundColor = UIColor.white.withAlphaComponent(offset)
UIApplication.shared.statusBarView?.backgroundColor = UIColor.red.withAlphaComponent(offset)
}
}
Put this extension wherever you want :
public extension UIImage {
convenience init(withBackground color: UIColor) {
let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size);
let context:CGContext = UIGraphicsGetCurrentContext()!;
context.setFillColor(color.cgColor);
context.fill(rect)
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.init(ciImage: CIImage(image: image)!)
}
}
It makes a UIImage using a UIColor. change the color alpha and set it as your navigationBar's backGroundImage. Here is a sample of how to use it:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
DispatchQueue.main.async {
var offset = scrollView.contentOffset.y
self.navigationController?.navigationBar.setBackgroundImage(UIImage(withBackground: UIColor.init(red: 0, green: 0, blue: 0, alpha: offset * 0.1)), for: .default)
}
}
let appearance = UINavigationBarAppearance()
appearance.backgroundColor = UIColor(named: "BackgroundColor")
appearance.titleTextAttributes = [.foregroundColor: UIColor(named: "TextColor") ?? .white]
self.navigationController?.navigationBar.scrollEdgeAppearance = appearance
self.navigationController?.navigationBar.standardAppearance = appearance

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 create a tab bar using SingleViewApplication 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)
}
}
}

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]
}
}
}
}
}

Resources