Animate a UINavigationBar's barTintColor - objective-c

The app I'm working on changes the barTintColor of its navigation bar when pushing new view controllers. Right now we set that colour in the destination view controller's viewWillAppear:method, but we have a few issues with that.
With the way we're doing this right now, the navigation bar's colour changes abruptly, while the rest of the bar content animates as usual. What I'd like is for the bar to fade between the source and destination colour. Is there any way to achieve this with public Cocoa Touch APIs?

You can add extra animations that match the timing and animation curve of the view controller transition using UIViewControllerTransitionCoordinator.
A view controller's transitionCoordinator will be set after a view controller's animation has started (so in viewWillAppear of the presented view controller). Add any extra animations using animateAlongsideTransition:completion: on the transition coordinator.
An example:
[[self transitionCoordinator] animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
self.navigationController.navigationBar.translucent = NO;
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
} completion:nil];

Here is a simpler fix. The issue with barTintColor not animating correctly on pop occurs when you try to set the navigation bar appearance in viewWillDisappear. The fix is to set it in willMove(toParentViewController:) instead.
The code below will produce a smooth fading transition during both push and pop, and regardless of whether it is initiated by a gesture or button tap. Tested on iOS 10 and 11.
This also works for animating barStyle.
import UIKit
class RedViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
self.title = "Red"
self.navigationController?.navigationBar.barTintColor = .red
self.navigationController?.navigationBar.tintColor = .white
}
override func willMove(toParentViewController parent: UIViewController?) {
self.navigationController?.navigationBar.barTintColor = .white
self.navigationController?.navigationBar.tintColor = nil
}
}

To get a smooth animation during both push and pop, I had to make the navigation bar transparent and animate my own background color view behind it.
Here's my UINavigationController subclass that handles it:
import Foundation
import UIKit
class ColorTransitionNavigationController: UINavigationController {
var navigationBarBackgroundView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Put a background view behind the navigation bar
navigationBarBackgroundView = UIView()
view.insertSubview(navigationBarBackgroundView, belowSubview: navigationBar)
// Make the navigation bar transparent
navigationBar.isTranslucent = true
navigationBar.setBackgroundImage(UIImage(), for: .default)
// Size the colored background to match the navigation bar
navigationBarBackgroundView.translatesAutoresizingMaskIntoConstraints = false
navigationBarBackgroundView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
navigationBarBackgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
navigationBarBackgroundView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
// I used a hard-coded 64 instead of constraining to the height of the navigation bar because
// when calling navigationController.setNavigationBarHidden(true), the height of the navigation bar becomes 0
navigationBarBackgroundView.heightAnchor.constraint(equalToConstant: 64.0).isActive = true
}
func setBarTintColor(color: UIColor, animated: Bool, transitionCoordinator: UIViewControllerTransitionCoordinator?) {
guard let transitionCoordinator = transitionCoordinator, animated else {
navigationBarBackgroundView.backgroundColor = color
return
}
transitionCoordinator.animateAlongsideTransition(in: view, animation: { [weak self] (context) in
let transition = CATransition()
transition.duration = context.transitionDuration
transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
self?.navigationBarBackgroundView.layer.add(transition, forKey: nil)
self?.navigationBarBackgroundView.backgroundColor = color
}, completion:nil)
}
}
Usage:
If you want a UIViewController to animate the navigation bar color when it appears, override viewWillAppear and call setBarTintColor.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let navigationController = navigationController as? ColorTransitionNavigationController else { return }
navigationController.setBarTintColor(color: UIColor.green, animated: animated, transitionCoordinator: transitionCoordinator)
}

Related

Presenting modal in iOS 13 with custom height

In iOS 13 there is a new behaviour for modal view controller when being presented.And I found the build-in App Photo presents a smaller model view controller.
How can I present a viewController with a custom size like this,and can slide up to a larger height?
Picture screenshots from system photo app.
Yes it is possible Presenting modal in iOS 13 with custom height.
You just need to add the below code into your Presenting modal
override func updateViewConstraints() {
self.view.frame.size.height = UIScreen.main.bounds.height - 150
self.view.frame.origin.y = 150
self.view.roundCorners(corners: [.topLeft, .topRight], radius: 10.0)
super.updateViewConstraints()
}
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
Answer in Swift
I was looking for a way to replicate that type of ViewController behaviour, albeit with basic UI and have found a rather simple solution.
Basically, you create a ViewController (CardViewContoller) with a transparent background and then add to it a card-like view with a UIPanGestureReconizer, that will enable you to drag it around and dismiss it with the ViewController.
To present you simply call present, setting the modalPresentationStyle to .overCurrentContext and modalTransitionStyle to .coverVertical:
let cardVC = CardViewController()
cardVC.modalPresentationStyle = .overCurrentContext
cardVC.modalTransitionStyle = .coverVertical
present(cardVC, animated: true, completion: nil)
The in CardViewController, which can be created programmatically or using Interface Builder, you add a UIPanGestureRecognizer to your card view (contentView):
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleDismiss(recognizer:)))
panGestureRecognizer.cancelsTouchesInView = false
contentView.addGestureRecognizer(panGestureRecognizer)
Then just add an #objc function that will respond to the UIPanGestureRecognizer:
#objc
func handleDismiss (recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .changed:
viewTranslation = recognizer.translation(in: view)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
guard self.viewTranslation.y > 0 else {return}
self.view.transform = CGAffineTransform(translationX: 0, y: self.viewTranslation.y)
})
case .ended:
if viewTranslation.y < swipeThreshold {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.view.transform = .identity
})
} else {
dismiss(animated: true, completion: nil)
}
default:
break
}
}
The swipeThreshold is a CGFloat variable with a value of your choosing (200 works great for me), that if the UIPanGestureRecognizer y translation exceeds, will trigger the dismissal of the ViewController along with all the elements.
Likewise, you can add a simple button that will dismiss the ViewController on .touchUpInside calling dismiss()
If you want, you can have a look at this repo, in which I have a sample project that exhibits this behaviour. That way you can build your own totally customisable cards.

How to get the coordinates of Hyperlink in UIWebview

I'm loading the pdf (Having multiple Hyperlinks) document in UIWebview. I have to show UIPopover over hyperlinks dynamically.
I'm able to capture the coordinates of hyperlink using TapGesture Action method
- (void)tapAction:(UITapGestureRecognizer *)sender
{
self.point = [sender locationInView:self.myWebView];
}
And presenting the UIPopover over hyperlink by using below method
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *rqstUrl = [request URL];
if (([[rqstUrl scheme] isEqualToString: #"https"] || [[rqstUrl scheme] isEqualToString: #"http"]) && (navigationType == UIWebViewNavigationTypeLinkClicked))
{
[self.myWebView stopLoading];
CGRect rect = CGRectMake(self.point.x,self.point.y-5, 5, 5);
UIPopoverController *popController = [[UIPopoverController alloc] initWithContentViewController:contentViewController];
popController.popoverContentSize = CGSizeMake(500, 200);
self.popController = popController;
self.popController.delegate =self;
UIPopoverArrowDirection direction = UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown;
self.popController.popoverLayoutMargins = UIEdgeInsetsMake(0, rect.origin.x, 1, 1);
[self.popController presentPopoverFromRect:rect inView:webView permittedArrowDirections:direction animated:YES];
}
return YES;
}
But the problem is if I tapped in two different locations within 1 or 2 seconds like First Tap is On Hyperlink and Second Tap is on "somewhere else in UIWebview", UIPopover is presenting at second tap location only not in hyperlink location.
I have to show UIPopover based on the Hyperlink position only, not in other location.How can I resolve this issue?
Use an overlay view
Replace your method to register the tap location by an overlay with a tap through. UITapGestureRecognizer has these limitations:
When a tap occurs outside of an hyperlink, it does registers its location, thanks to the UITapGestureRecognizer.
Unfortunately, a UIWebview Hyperlink taps take precedence over the gesture recognizer, and you never get the centroid. This is the real problem, causing the popover to appear misplaced.
UIPopoverController is deprecated in iOS 9.
"UIPopoverController is deprecated. Popovers are now implemented as UIViewController presentations. Use a modal presentation style of UIModalPresentationPopover and UIPopoverPresentationController."
tapAction and shouldStartLoadWithRequest are not coupled, and can occur independently of each other. Furthermore, they are basically mutually exclusive.
Use the overlay to register location in that view, and tap-though to the views underneath. If your overlay and web view have the same frame, you can use the tap position interchangeably. The overlay will guarantee tight coupling, and the rest of your method will work as designed.
class TapOverlayView: UIView {
var centroid:CGRect = CGRect.zero
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
centroid = CGRect(origin: point, size: CGSize(width: 1, height: 1))
return nil // tap through
}
}
Delegate
extension ViewController: UIWebViewDelegate {
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let rqstUrl = request.url
if( rqstUrl!.scheme?.contains("http"))! && ( .linkClicked == navigationType) {
webView.stopLoading()
let contentViewController = storyboard!.instantiateViewController(withIdentifier: "popover")
contentViewController.modalPresentationStyle = .popover
contentViewController.preferredContentSize = CGSize(width: 200, height: 40)
if let popController = contentViewController.popoverPresentationController {
popController.permittedArrowDirections = .down
popController.sourceView = webView
popController.sourceRect = CGRect(origin: tap.centroid.origin, size: CGSize.zero)
present(contentViewController, animated: true, completion: nil)
}
}
return true
}
}
► Find this solution on GitHub and additional details on Swift Recipes.

UITextView text content doesn't start from the top

I have a long text coming from my JSON file but when I click the link from my UITableViewCell to go to my UIViewController page, the UITextView text loads the string content but it does not show the content from the beginning and I have to scroll up all the time.
What I need to do?
I had the same problem, and turns out I had to set the content offset in viewDidLayoutSubviews for it to take effect. I'm using this code to display attributed static text.
- (void)viewDidLayoutSubviews {
[self.yourTextView setContentOffset:CGPointZero animated:NO];
}
SWIFT 3:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.textView.setContentOffset(CGPoint.zero, animated: false)
}
This is the only way that worked for me. I disable the scroll of the UITextView before the view is loaded and then i enable it again:
override func viewWillAppear(_ animated: Bool) {
yourTextView.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
yourTextView.isScrollEnabled = true
}
[self.textView scrollRangeToVisible:NSMakeRange(0, 1)];
in viewDidLoad
By Programmatically before loading the content disable the scrolling property of textview
textview.scrollenabled = NO;
And after loading enable the scrolling of textview textview.scrollenabled = YES;
As well check the XIB, always non-check the scrolling enabled of Textview.
The answers for the question Blank space at top of UITextView in iOS 10 provide a much cleaner end user experience.
In viewDidLoad of the view controller containing the text view:
self.automaticallyAdjustsScrollViewInsets = false
Setting textView.setContentOffset(CGPointMake(0,0), animated: false) and some of these other suggestions do work when called in the viewDidLayoutSubviews() but on older devices like iPad 2 and older you will actually see the text get scrolled when the screen is displayed. That is not something you want the end user to see.
I was still having problems after using these solutions. The problem definitely seems to relate to having transparent navigation bars and selecting to automatically adjust content insets on the view controller. If you don't care about your text scrolling underneath the navigation bar then it's best to leave these settings off and constrain the top of your textview to the bottom of the navigation bar, rather than to the top of the viewcontroller.
If like me you wanted it to appear underneath your navigation bar when you scroll down; then the solution that worked for me was to add this.
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
CGFloat offset = self.navigationController.navigationBar.frame.size.height+[UIApplication sharedApplication].statusBarFrame.size.height;
[self.textView setContentOffset:CGPointMake(0, -offset) animated:NO];
}
This just looks for the height of the navigation bar and status bar and adjusts the content offset accordingly.
Note that one downside of this approach is that when the device rotates you'll end up scrolling back to the top.
For me fine works this code:
textView.attributedText = newText //or textView.text = ...
//this part of code scrolls to top
textView.contentOffset.y = -64 //or = 0 if no Navigation Bar
textView.scrollEnabled = false
textView.layoutIfNeeded()
textView.scrollEnabled = true
For scroll to exact position and show it on top of screen I use this code:
var scrollToLocation = 50 //<needed position>
textView.contentOffset.y = textView.contentSize.height
textView.scrollRangeToVisible(NSRange.init(location: scrollToLocation, length: 1))
Setting contentOffset.y scrolls to the end of text, and then scrollRangeToVisible scrolls up to value of scrollToLocation. Thereby, needed position appears in first line of scrollView.
Similar to some other answers, but with the added benefit that you won't cause a scroll to top on subsequent device rotations. Works well in Swift 2.2
/// Whether view has laid out subviews at least once before.
var viewDidLayoutSubviewsAtLeastOnce = false
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if !viewDidLayoutSubviewsAtLeastOnce {
textView.setContentOffset(CGPoint(x: 0, y: -textView.contentInset.top), animated: false)
}
viewDidLayoutSubviewsAtLeastOnce = true
}
Swift Version
A combination of things will be needed:
1.) Set your outlet
#IBOutlet var textView: UITextView!
2.) In storyboard on View Controller turn off "Adjust Scroll View Insets"
3.) Set content to zero top by adding below to your view controller
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
myUITextView.setContentOffset(CGPointZero, animated: false)
}
Instead of setting content offset from viewDidLayoutSubviews you can write layoutIfNeeded from viewDidLoad to set the proper position of textview as below:
self.textView.layoutIfNeeded()
self.textView.setContentOffset(CGPoint.zero, animated: false)
Cheers !!
In Swift 2, Xcode 7 solution, to leave scroll Enabled as well as have the text start at the top, this is all you need:
#IBOutlet weak var myUITextView: UITextView!
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
//start scroll at top of text
myUITextView.scrollRangeToVisible(NSMakeRange(0, 0))
}
Swift 3.0
override func viewWillAppear(_ animated: Bool) {
privacyText.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
privacyText.isScrollEnabled = true
}
This worked the best for me! I placed this within viewDidLoad().
//TextView Scroll starts from the top
myTextView.contentOffset.y = 0
Here's another way to do it that always works for me. Objective-C:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self.textView setContentOffset:CGPointZero animated:NO];
}
And in Swift:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
textView.setContentOffset(CGPointZero, animated: false)
}
Swift version:
override func viewDidLayoutSubviews() {
yourTextView.setContentOffset(CGPointZero, animated: false)
}
add the following function to your view controller class...
Swift 3
override func viewDidLayoutSubviews() {
self.mainTextView.setContentOffset(.zero, animated: false)
}
Swift 2.1
override func viewDidLayoutSubviews() {
self.mainTextView.setContentOffset(CGPointZero, animated: false)
}
Objective C
- (void)viewDidLayoutSubviews {
[self.mainTextView setContentOffset:CGPointZero animated:NO];
}
或者 你在ViewDidAppear 里面加上滚动,这样用户会看到他往上滚动到第一行
in swift 4 with attributed text any of answer does not help me and i combine some answers in topic.
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
uiTextview.isScrollEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
uiTextview.isScrollEnabled = true
uiTextview.setContentOffset(CGPoint.zero, animated: false)
}
Swift 3, 4, 5 solution:
Steps to solve the issue:
Disable the UITextView scroll
set scrollRectToVisible
enable UITextView scroll
Code:
yourTextView.isScrollEnabled = false
let rect:CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
yourTextView.scrollRectToVisible(rect, animated: false)
yourTextView.isScrollEnabled = true
This Worked for me. Hope that will help!
This is how i did it. I subclassed textview, and:
override func willMoveToSuperview(newSuperview: UIView?) {
self.scrollEnabled = false
}
override func layoutSubviews() {
super.layoutSubviews()
self.scrollEnabled = true
}
From storyboard, select the view controller on which you have you text view placed. In the attributes inspector, uncheck "Adjust Scroll View Insets". That's it.
Put this code on your class
override func viewDidLayoutSubviews() {
self.About_TV.setContentOffset(.zero, animated: false) // About_TV : your text view name)
}
Add code to the viewdidload
self.automaticallyAdjustsScrollViewInsets = NO;

Cursor not displaying in UISearchBar for our app

For the UISearchBars in our app, there's no cursor shown in the bar with focus when running under iOS 7. How do we make that show?
We are using the SDK 7, with a minimum target of 6. We do have the translucency off for the navigation bars, and set the color at runtime. I can't think of anything else we are doing differently.
Our problem was that the tint color was set to white, so I didn't see it.
Set
searchBar.tintColor = [UIColor blueColor];
In the searchbox property window
open View Section>Set Tint color - default.
Hope this will help.
This is how it can be done in Swift :
override func viewWillAppear(animated: Bool) {
self.searchBar.tintColor = UIColor.whiteColor()
let view: UIView = self.searchBar.subviews[0] as! UIView
let subViewsArray = view.subviews
for (subView: UIView) in subViewsArray as! [UIView] {
println(subView)
if subView.isKindOfClass(UITextField){
subView.tintColor = UIColor.blueColor()
}
}
}
searchBar.tintColor = view.tintColor // self.view usually has the proper tintColor
Better than .blue or whatever.
Just set the tintColor for UISearchBar, in your storyboard, xib or code. Xcode seems to ignore the default tintColor.
You could loop through the searchBars subviews and obtain the uitextfield subview and set its #"insertionPointColor" value to your desired color. Works but is private api
for (UIView *subView in self.searchBar.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
[[(UITextField *) subView valueForKey:#"textInputTraits"] setValue:[UIColor blackColor] forKey:#"insertionPointColor"];
}
}

Hide NSWindow title bar

Is there a way to hide the titlebar in an NSWindow? I don't want to have to completely write a new custom window. I can't use NSBorderlessWindowMask because I have a bottom bar on my window, and using NSBorderlessWindowMask makes that disappear. I also tried using setContentBorderThickness:forEdge: with NSMaxYEdge and setting it to 0, that didn't work either.
Any help is appreciated
[yourWindow setStyleMask:NSBorderlessWindowMask];
Starting from OS X 10.10, you can hide title bar.
window1.titlebarAppearsTransparent = true
window1.titleVisibility = .Hidden
Maybe you want to override window style.
window1.styleMask = NSResizableWindowMask
| NSTitledWindowMask
| NSFullSizeContentViewWindowMask
Kind of Welcome screen NSWindow / NSViewController setup (Swift 4.1)
extension NSWindow {
enum Style {
case welcome
}
convenience init(contentRect: CGRect, style: Style) {
switch style {
case .welcome:
let styleMask: NSWindow.StyleMask = [.closable, .titled, .fullSizeContentView]
self.init(contentRect: contentRect, styleMask: styleMask, backing: .buffered, defer: true)
titlebarAppearsTransparent = true
titleVisibility = .hidden
standardWindowButton(.zoomButton)?.isHidden = true
standardWindowButton(.miniaturizeButton)?.isHidden = true
}
}
}
class WelcomeWindowController: NSWindowController {
private (set) lazy var viewController = WelcomeViewController()
private let contentWindow: NSWindow
init() {
contentWindow = NSWindow(contentRect: CGRect(x: 400, y: 200, width: 800, height: 472), style: .welcome)
super.init(window: contentWindow)
let frameSize = contentWindow.contentRect(forFrameRect: contentWindow.frame).size
viewController.view.setFrameSize(frameSize)
contentWindow.contentViewController = viewController
}
}
class WelcomeViewController: NSViewController {
private lazy var contentView = View()
override func loadView() {
view = contentView
}
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
contentView.backgroundColor = .white
}
}
class View: NSView {
var backgroundColor: NSColor?
convenience init() {
self.init(frame: NSRect())
}
override func draw(_ dirtyRect: NSRect) {
if let backgroundColor = backgroundColor {
backgroundColor.setFill()
dirtyRect.fill()
} else {
super.draw(dirtyRect)
}
}
}
Result
What happens if you get the superview of the close button? Can you hide that?
// Imagine that 'self' is the NSWindow derived class
NSButton *miniaturizeButton = [self standardWindowButton:NSWindowMiniaturizeButton];
NSView* titleBarView = [miniaturizeButton superview];
[titleBarView setHidden:YES];
The only way I know would be to create a window without a titlebar (see
NSBorderlessWindowMask). Note that you can't (easily) create a window without a
titlebar in IB, so you will have to do a bit of work in code (there are a
couple of different approaches, you can probably figure it out).
A big drawback with using a window without a titlebar is that you're now on the
hook for much more of the standard appearance and behaviour - rounded corners
and such.
I had an experience that when I first set content view of my window and then set the window borderless:
[yourWindow setStyleMask:NSBorderlessWindowMask];
Nothing would appear in my window. So i first set the style mask and after that i've set the content view:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// 1. borderless window
[[self window] setStyleMask: NSBorderlessWindowMask];
// 2. create the master View Controller
self.masterViewController = [[MasterViewController alloc] initWithNibName:#"MasterViewController" bundle:nil];
// 3. Add the view controller to the Window's content view
[self.window.contentView addSubview:self.masterViewController.view];
self.masterViewController.view.frame = ((NSView*)self.window.contentView).bounds;
}
And voila, the content of my window has appeared.
Select Window in storyboard or XIB and tick the red circled option.
You can use WAYInAppStoreWindow available on GitHub which works on Yosemite and Mavericks.
Swift
NSApp.mainWindow?.styleMask = .borderless