make UIImage fill the entire navigationBar - ios

I want to insert an image inside a ui navigation bar and make it look as an aspect fit image looks inside an imageView.
i am doing it as
navigationController?.navigationBar.compactAppearance?.backgroundImageContentMode = .scaleToFill
navigationController?.navigationBar.setBackgroundImage(image, for: .default)
But it is giving me the output as :
How can i make it perfect.

The simplest way to use the UIImageView here with scaleAspectFit image property. Try the following working code block.
func setNavigation() {
let imageView = UIImageView(image: UIImage(named: "bankselected"))
imageView.frame = navigationController!.navigationBar.frame
imageView.backgroundColor = .lightGray
imageView.contentMode = .scaleAspectFit
navigationController?.navigationBar.addSubview(imageView)
}

You can use this Protocol to add image in your navigationBar
protocol CustomizableNavigationBar {
var navigationBar: UINavigationBar? { get }
}
extension CustomizableNavigationBar {
func setNavBarLogo() {
let imageView = UIImageView(image: UIImage(named: "artistAvatar1"))
imageView.frame = navigationBar!.frame
imageView.contentMode = .scaleToFill
navigationBar?.addSubview(imageView)
}
}
Use it like This
class SearchViewController: UIViewController,CustomizableNavigationBar {
var navigationBar: UINavigationBar?
override func viewDidLoad() {
super.viewDidLoad()
navigationBar = navigationController?.navigationBar
setNavBarLogo()
}
}

Related

change page Indicator Image [SMPageControl] / EAIntroView in swift

I'm trying to change the indicator image , following the example in EAIntroView
here is the objective-c code from EAIntroView
SMPageControl *pageControl = [[SMPageControl alloc] init];
pageControl.pageIndicatorImage = [UIImage imageNamed:#"pageDot"];
pageControl.currentPageIndicatorImage = [UIImage imageNamed:#"selectedPageDot"];
[pageControl sizeToFit];
intro.pageControl = (UIPageControl *)pageControl;
intro.pageControlY = 130.f;
and here is the swift code I'm trying to implement
// SMPageControl
pageControl = SMPageControl()
pageControl.pageIndicatorImage = UIImage(named: "pageDot")
pageControl.currentPageIndicatorImage = UIImage(named: "selectedPageDot")
pageControl.sizeToFit()
pageControl.backgroundColor = UIColor.clearColor()
intro.pageControl = pageControl as? UIPageControl
swift code has a warning here
intro.pageControl = pageControl as? UIPageControl
the warning is :
Cast from 'SMPageControl!' to unrelated type 'UIPageControl' always fails
any help ?
For changing page Indicator Image [SMPageControl] / EAIntroView in swift I have created custom class of UIPageControl like below:
import UIKit
class CustomPageControl: UIPageControl {
let activePage: UIImage = UIImage(named: "icon-selected-dot")!
let inActivePage: UIImage = UIImage(named: "icon-dot")!
override var numberOfPages: Int {
didSet {
updateDots()
}
}
override var currentPage: Int {
didSet {
updateDots()
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.pageIndicatorTintColor = UIColor.clear
self.currentPageIndicatorTintColor = UIColor.clear
self.clipsToBounds = false
}
func updateDots() {
var i = 0
for view in self.subviews {
var imageView = self.imageView(forSubview: view)
if imageView == nil {
if i == self.currentPage {
imageView = UIImageView(image: activePage)
} else {
imageView = UIImageView(image: inActivePage)
}
imageView!.center = view.center
view.addSubview(imageView!)
view.clipsToBounds = false
}
if i == self.currentPage {
imageView!.alpha = 1.0
imageView?.image = activePage
} else {
imageView!.alpha = 0.5
imageView?.image = inActivePage
}
i += 1
}
}
fileprivate func imageView(forSubview view: UIView) -> UIImageView? {
var dot: UIImageView?
if let dotImageView = view as? UIImageView {
dot = dotImageView
} else {
for foundView in view.subviews {
if let imageView = foundView as? UIImageView {
dot = imageView
break
}
}
}
return dot
}
}
then in your class just add these lines and you can use custom images for dot
//Custom page Control
let pageControl = CustomPageControl()
pageControl.updateDots()
intro.pageControl = pageControl
Hope it will work for you! #ynamao
You can see from the source code of SMPageControl that it isn't a subclass of UIPageControl. Which means the error is expected: UIPageControl is a completely unrelated type, to which the value cannot be cast.
The Objective-C you pointed to might work, but it's bad and wrong: inline cast to UIPageControl achieves nothing here and can cause internal inconsistencies.
This is exactly the kind of sloppiness that Swift compiler is designed to prevent, and it's doing its job well.
Your best bet is to forgo using this library in Swift code.

image scaling for UITabBar background image

I've created UITabBarController in my application.
Then in viewDidLoad() I want to change UITabBar background image. Here is the code I'm trying to make it works:
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().translucent = false
UITabBar.appearance().backgroundColor = UIColor.clearColor()
UITabBar.appearance().backgroundImage = UIImage(named: "tabbar_background")
UITabBar.appearance().contentMode = .ScaleAspectFit
}
}
But the result isn't correct (image). Can someone help me to make it fill the entire tabbar frame?
I solved this problem using clipsToBounds.
Here are my example:
let tabBar = self.tabBar
tabBar.backgroundImage = UIImage()
tabBar.clipsToBounds = true
This work perfectly on iPhone X
Try resizing the image to the tab bar size. Or Add an imageView to the tabBar as subview, and then use the image in that imageView.
Subclass the TabBarController and add imageview there:
var bgView: UIImageView = UIImageView(image: UIImage(named: "tabBarBackground.png"))
bgView.frame = CGRectMake(0, 420, 320, 60)//you might need to modify this frame to your tabbar frame
self.view.addSubview(bgView)
This works for me in swift 3
class MyTabBarController: UITabBarController, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let backgroundImage = UIImageView(image: UIImage(named: "gray background"))
backgroundImage.frame = backgroundImage.bounds
self.view.addSubview(backgroundImage)
}
Here is code for a custom translucent tab bar image with custom icons. You will need to refer directly to the tab bar via a variable.
Swift 3
private func setupTabBar() {
print ("Setting up the Tab Bar and Items")
tabBarView.clipsToBounds = true
tabBarView.backgroundImage = UIImage()
let bgView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "TabBarBackground"))
bgView.frame = tabBarView.bounds
tabBarView.addSubview(bgView)
tabBarView.tintColor = UIColor.white
UITabBar.appearance().tintColor = UIColor.gray
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.gray], for: .selected)
tabBarLimitsItemView.image = #imageLiteral(resourceName: "TabIconLimits").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
tabBarControlsItemView.image = #imageLiteral(resourceName: "TabIconControls").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
tabBarPayRulesItemView.image = #imageLiteral(resourceName: "TabIconPayRules").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
tabBarSettingsItemView.image = #imageLiteral(resourceName: "TabIconSettings").withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}

How do I share a UIImage between two ViewControllers programmatically?

I'm using this custom collectionView transition:
When a cell is selected, the UIImage in the cell is animated to transition seamlessly into the UIImageView in the detailViewController ,as seen in the GIF in this link.
However the issue is, the UIImage in the detailViewController's UIImageView is hard coded in, and will be the same for every selected cell from the UICollectionView. I have different images within my collectionViewCell's and this would obviously be a problem, so I need to somehow programmatically make my detailViewController's UIImageView Image to equal that of the selected collectionViewCell's UIImageView Image when the transition is completed.
Here's the code I used to try to achieve this:
class DetailViewController: UIViewController, ARNImageTransitionZoomable {
#IBOutlet weak var imageView: UIImageView!
var selectedCell = MasterCollectionViewController()
deinit {
println("deinit DetailViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
imageView.layer.cornerRadius = 3.0
imageView.clipsToBounds = true
}
// MARK: - ARNImageTransitionZoomable
func createTransitionImageView() -> UIImageView {
var imageView = UIImageView(image: self.imageView.image)
imageView.contentMode = self.imageView.contentMode
imageView.clipsToBounds = true
imageView.userInteractionEnabled = false
imageView.frame = self.imageView!.frame
return imageView
}
func presentationBeforeAction() {
self.imageView.hidden = true
}
func presentationCompletionAction(completeTransition: Bool) {
self.imageView.hidden = false
self.imageView.image = selectedCell.selectedImageView?.image
}
func dismissalBeforeAction() {
self.imageView.hidden = true
}
func dismissalCompletionAction(completeTransition: Bool) {
if !completeTransition {
self.imageView.hidden = false
}
}
}
I added a variable "selectedCell" that is of type MasterCollectionViewController(), giving me reference to everything in that class.
Then in the animation/transitions completion, I attempted to set the selected cell's UIImage to that of my detailViewController's UIImageView Image with the line
func presentationCompletionAction(completeTransition: Bool) {
self.imageView.hidden = false
self.imageView.image = selectedCell.selectedImageView?.image
}
This didn't work, when the transition is complete, the UIImageView is just white with no image, just as it is on my storyboard. Somebody know any method I can implement?

Stretch Background for View in Swift

I am using adding Background in iOS Swift App using:
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background")!)
However, it does not cover the Screen till bottom. I searched Other questions:
var backImage = UIImage(named: "background")
var resizablebackImage = backImage?.resizableImageWithCapInsets(UIEdgeInsets(top:10,left:0,bottom:10,right:0))
self.view.backgroundColor = UIColor(patternImage:resizablebackImage!)
That does not work. Any ideas?
If your intention is to set it as the background image, don't make image as pattern color and fill it as background color. Instead create an UIImageView set your image as it's image and add it to your UIView.
var bgImage = UIImage(named: "background");
var imageView = UIImageView(frame: self.view.bounds);
imageView.image = bgImage
self.view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
For Swift 1.x & Swift 2 plus Device Rotation Detection
Please see my code below. Just set bgImageName to the name of your image and call setBackgroundImage(). I added an auto-reload in case of a device rotation.
var bgImage = UIImage()
var bgImageView = UIImageView()
var bgImageName = ""
override func viewDidLoad() {
super.viewDidLoad()
bgImageName = "bg-orange" // or whatever your image is called
setBackgroundImage()
}
func setBackgroundImage() {
if bgImageName > "" {
bgImageView.removeFromSuperview()
bgImage = UIImage(named: bgImageName)!
bgImageView = UIImageView(frame: self.view.bounds)
bgImageView.image = bgImage
self.view.addSubview(bgImageView)
self.view.sendSubviewToBack(bgImageView)
}
}
// detect device orientation changes
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if UIDevice.currentDevice().orientation.isLandscape.boolValue {
print("rotated device to landscape")
setBackgroundImage()
} else {
print("rotated device to portrait")
setBackgroundImage()
}
}

How to hide UINavigationBar 1px bottom line

I have an app that sometimes needs its navigation bar to blend in with the content.
Does anyone know how to get rid of or to change color of this annoying little bar?
On the image below situation i have - i'm talking about this 1px height line below "Root View Controller"
For iOS 13:
Use the .shadowColor property
If this property is nil or contains the clear color, the bar displays no shadow
For instance:
let navigationBar = navigationController?.navigationBar
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.shadowColor = .clear
navigationBar?.scrollEdgeAppearance = navigationBarAppearance
For iOS 12 and below:
To do this, you should set a custom shadow image. But for the shadow image to be shown you also need to set a custom background image, quote from Apple's documentation:
For a custom shadow image to be shown, a custom background image must
also be set with the setBackgroundImage(_:for:) method. If the default
background image is used, then the default shadow image will be used
regardless of the value of this property.
So:
let navigationBar = navigationController!.navigationBar
navigationBar.setBackgroundImage(#imageLiteral(resourceName: "BarBackground"),
for: .default)
navigationBar.shadowImage = UIImage()
Above is the only "official" way to hide it. Unfortunately, it removes bar's translucency.
I don't want background image, just color##
You have those options:
Solid color, no translucency:
navigationBar.barTintColor = UIColor.redColor()
navigationBar.isTranslucent = false
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
Create small background image filled with color and use it.
Use 'hacky' method described below. It will also keep bar translucent.
How to keep bar translucent?##
To keep translucency you need another approach, it looks like a hack but works well. The shadow we're trying to remove is a hairline UIImageView somewhere under UINavigationBar. We can find it and hide/show it when needed.
Instructions below assume you need hairline hidden only in one controller of your UINavigationController hierarchy.
Declare instance variable:
private var shadowImageView: UIImageView?
Add method which finds this shadow (hairline) UIImageView:
private func findShadowImage(under view: UIView) -> UIImageView? {
if view is UIImageView && view.bounds.size.height <= 1 {
return (view as! UIImageView)
}
for subview in view.subviews {
if let imageView = findShadowImage(under: subview) {
return imageView
}
}
return nil
}
Add/edit viewWillAppear/viewWillDisappear methods:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if shadowImageView == nil {
shadowImageView = findShadowImage(under: navigationController!.navigationBar)
}
shadowImageView?.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
shadowImageView?.isHidden = false
}
The same method should also work for UISearchBar hairline,
and (almost) anything else you need to hide :)
Many thanks to #Leo Natan for the original idea!
Here is the hack. Since it works on key paths might break in the future. But for now it works as expected.
Swift:
self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
Objective C:
[self.navigationController.navigationBar setValue:#(YES) forKeyPath:#"hidesShadow"];
If you just want to use a solid navigation bar color and have set this up in your storyboard, use this code in your AppDelegate class to remove the 1 pixel border via the appearance proxy:
[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init]
forBarPosition:UIBarPositionAny
barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];
Try this:
[[UINavigationBar appearance] setBackgroundImage: [UIImage new]
forBarMetrics: UIBarMetricsDefault];
[UINavigationBar appearance].shadowImage = [UIImage new];
Below image has the explanation (iOS7 NavigationBar):
And check this SO question:
iOS7 - Change UINavigationBar border color
The swift way to do it:
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()
Wanted to add the Swift version of Serhii's answer. I created a UIBarExtension.swift with the following:
import Foundation
import UIKit
extension UINavigationBar {
func hideBottomHairline() {
self.hairlineImageView?.isHidden = true
}
func showBottomHairline() {
self.hairlineImageView?.isHidden = false
}
}
extension UIToolbar {
func hideBottomHairline() {
self.hairlineImageView?.isHidden = true
}
func showBottomHairline() {
self.hairlineImageView?.isHidden = false
}
}
extension UIView {
fileprivate var hairlineImageView: UIImageView? {
return hairlineImageView(in: self)
}
fileprivate func hairlineImageView(in view: UIView) -> UIImageView? {
if let imageView = view as? UIImageView, imageView.bounds.height <= 1.0 {
return imageView
}
for subview in view.subviews {
if let imageView = self.hairlineImageView(in: subview) { return imageView }
}
return nil
}
}
Simple solution in swift
let navigationBar = self.navigationController?.navigationBar
navigationBar?.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
navigationBar?.shadowImage = UIImage()
As of iOS 13 there is a system API to set or remove the shadow
UIKit uses shadowImage and the shadowColor property to determine the shadow's
appearance. When shadowImage is nil, the bar displays a default shadow tinted
according to the value in the shadowColor property. If shadowColor is nil or
contains the clearColor color, the bar displays no shadow.
let appearance = UINavigationBarAppearance()
appearance.shadowImage = nil
appearance.shadowColor = nil
navigationController.navigationBar.standardAppearance = appearance
https://developer.apple.com/documentation/uikit/uibarappearance/3198009-shadowimage
Can also be hidden from Storyboard (working on Xcode 10.1)
By adding runtime attribute: hidesShadow - Boolean - True
In Swift 3.0
Edit your AppDelegate.swift by adding the following code to your application function:
// Override point for customization after application launch.
// Remove border in navigationBar
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
After studying the answer from Serhil, I created a pod UINavigationBar+Addition that can easily hide the hairline.
#import "UINavigationBar+Addition.h"
- (void)viewDidLoad {
[super viewDidLoad];
UINavigationBar *navigationBar = self.navigationController.navigationBar;
[navigationBar hideBottomHairline];
}
Swift 4
//for hiding navigation bar shadow line
navigationController?.navigationBar.shadowImage = UIImage()
pxpgraphics' solution updated for Swift 2.0
extension UINavigationBar {
func hideBottomHairline()
{
hairlineImageViewInNavigationBar(self)?.hidden = true
}
func showBottomHairline()
{
hairlineImageViewInNavigationBar(self)?.hidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView?
{
if let imageView = view as? UIImageView where imageView.bounds.height <= 1
{
return imageView
}
for subview: UIView in view.subviews
{
if let imageView = hairlineImageViewInNavigationBar(subview)
{
return imageView
}
}
return nil
}
}
extension UIToolbar
{
func hideHairline()
{
let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = true
}
func showHairline()
{
let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = false
}
private func hairlineImageViewInToolbar(view: UIView) -> UIImageView?
{
if let imageView = view as? UIImageView where imageView.bounds.height <= 1
{
return imageView
}
for subview: UIView in view.subviews
{
if let imageView = hairlineImageViewInToolbar(subview)
{
return imageView
}
}
return nil
}
}
I use a UINavigationBar extension that enables me to hide/show that shadow using the UIAppearance API or selecting which navigation bar has to hide/show that shadow using Storyboard (or source code). Here is the extension:
import UIKit
private var flatAssociatedObjectKey: UInt8 = 0
/*
An extension that adds a "flat" field to UINavigationBar. This flag, when
enabled, removes the shadow under the navigation bar.
*/
#IBDesignable extension UINavigationBar {
#IBInspectable var flat: Bool {
get {
guard let obj = objc_getAssociatedObject(self, &flatAssociatedObjectKey) as? NSNumber else {
return false
}
return obj.boolValue;
}
set {
if (newValue) {
let void = UIImage()
setBackgroundImage(void, forBarPosition: .Any, barMetrics: .Default)
shadowImage = void
} else {
setBackgroundImage(nil, forBarPosition: .Any, barMetrics: .Default)
shadowImage = nil
}
objc_setAssociatedObject(self, &flatAssociatedObjectKey, NSNumber(bool: newValue),
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
Now, to disable the shadow across all navigation bars you have to use:
UINavigationBar.appearance().flat = true
Or you can enable/disable this behavior using storyboards:
Swift 4 Tested
ONE LINE SOLUTION
In Viewdidload()
Set Navigation controller's userdefault value true for key "hidesShadow"
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
}
For iOS 13+
The trick is to initialize 'UINavigationBarAppearance' with TransparentBackground. Then you could easily remove the horizontal line of the navigation bar.
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = .green // Required background color
Finally, add the appearance changes to the navigation item as the apple suggested.
self.navigationItem.standardAppearance = appearance
self.navigationItem.scrollEdgeAppearance = appearance
self.navigationItem.compactAppearance = appearance
Swift put this
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: .Any, barMetrics: .Default)
UINavigationBar.appearance().shadowImage = UIImage()
in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
Another option if you want to preserve translucency and you don't want to subclass every UINavigationController in your app:
#import <objc/runtime.h>
#implementation UINavigationController (NoShadow)
+ (void)load {
Method original = class_getInstanceMethod(self, #selector(viewWillAppear:));
Method swizzled = class_getInstanceMethod(self, #selector(swizzled_viewWillAppear:));
method_exchangeImplementations(original, swizzled);
}
+ (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
- (void)swizzled_viewWillAppear:(BOOL)animated {
UIImageView *shadow = [UINavigationController findHairlineImageViewUnder:self.navigationBar];
shadow.hidden = YES;
[self swizzled_viewWillAppear:animated];
}
#end
Slightly Swift Solution
func setGlobalAppearanceCharacteristics () {
let navigationBarAppearace = UINavigationBar.appearance()
navigationBarAppearace.tintColor = UIColor.white
navigationBarAppearace.barTintColor = UIColor.blue
navigationBarAppearace.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navigationBarAppearace.shadowImage = UIImage()
}
Two lines solution that works for me. Try to add this in ViewDidLoad method:
navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
self.extendedLayoutIncludesOpaqueBars = true
Here's a very simple solution:
self.navigationController.navigationBar.clipsToBounds = YES;
In iOS8, if you set the UINavigationBar.barStyle to .Black you can set the bar's background as plain color without the border.
In Swift:
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().barStyle = UIBarStyle.Black
UINavigationBar.appearance().barTintColor = UIColor.redColor()
Solution in Swift 4.2:
private func removeHairlineFromNavbar() {
UINavigationBar.appearance().setBackgroundImage(
UIImage(),
for: .any,
barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()
}
Just put this function at the first Viewcontroller and call it in viewdidload
Simple solution – Swift 5
Create an extension:
extension UIImage {
class func hideNavBarLine(color: UIColor) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let navBarLine = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return navBarLine
}
}
Add this to viewDidLoad():
self.navigationController?.navigationBar.shadowImage = UIImage.hideNavBarLine(color: UIColor.clear)
For iOS 9 users, this worked for me. just add this:
UINavigationBar.appearance().shadowImage = UIImage()
The problem with setting a background image is it removes blurring. You can remove it without setting a background image. See my answer here.
pxpgraphics's answer for Swift 3.0.
import Foundation
import UIKit
extension UINavigationBar {
func hideBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
navigationBarImageView!.isHidden = true
}
func showBottomHairline() {
let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
navigationBarImageView!.isHidden = false
}
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
if view is UIImageView && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
return imageView
}
}
return nil
}
}
extension UIToolbar {
func hideHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = true
}
func showHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = false
}
private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? {
if view is UIImageView && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) {
return imageView
}
}
return nil
}
}
You should add a view to a bottom of the UISearchBar
let rect = searchController.searchBar.frame;
let lineView : UIView = UIView.init(frame: CGRect.init(x: 0, y: rect.size.height-1, width: rect.size.width, height: 1))
lineView.backgroundColor = UIColor.init(hexString: "8CC73E")
searchController.searchBar.addSubview(lineView)
I Just created an extension for this... Sorry about formatting (this is my first answer).
Usage:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.hideShadow = true
}
Extension:
UINavigationController.swift
// Created by Ricardo López Rey on 16/7/15.
import Foundation
struct UINavigationControllerExtension {
static var hideShadowKey : String = "HideShadow"
static let backColor = UIColor(red: 247/255, green: 247/255, blue: 248/255, alpha: 1.0)
}
extension UINavigationController {
var hideShadow : Bool {
get {
if let ret = objc_getAssociatedObject(self, &UINavigationControllerExtension.hideShadowKey) as? Bool {
return ret
} else {
return false
}
}
set {
objc_setAssociatedObject(self,&UINavigationControllerExtension.hideShadowKey,newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
if newValue {
self.navigationBar.setBackgroundImage(solidImage(UINavigationControllerExtension.backColor), forBarMetrics: UIBarMetrics.Default)
self.navigationBar.shadowImage = solidImage(UIColor.clearColor())
} else {
self.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default)
}
}
}
private func solidImage(color: UIColor, size: CGSize = CGSize(width: 1,height: 1)) -> UIImage {
var rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Within AppDelegate, this has globally changed the format of the NavBar:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().tintColor = UIColor.whiteColor()
UINavigationBar.appearance().barTintColor = UIColor.redColor()
UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().clipsToBounds = false
UINavigationBar.appearance().backgroundColor = UIColor.redColor()
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : (UIFont(name: "FONT NAME", size: 18))!, NSForegroundColorAttributeName: UIColor.whiteColor()] }
Haven't managed to implement anything different on a specific VC, but this will help 90% of people

Resources