How to use toast method in app delegate functions using swift - swift

Hi am developing app using swift in my app I want use toast message and toast activity so i followed the link: https://github.com/scalessec/Toast-Swift. I am able to use in view controller method it works well but I can't use in app delegate methods.
My code in my app delegate:
func loadJsonData(){
self.view.makeToastActivity(.center)
}
The above mentioned code does not work because app delegate has no member view...please help me to use that in my app delegate.

AppDelegate is for handling things like initialising the app, closing the app, notifications, etc.
What you want to do is:
Go to the storyboard (named Main.storyboard)
Add a ViewController to the storyboard (drag it from the bottom right)
Create a Swift file and call it FirstView, for example, and add the following code
FirstView.swift
import UIKit
class FirstView: UIViewController
{
override func viewDidLoad()
{
self.view.makeToastActivity(.center);
}
}
Go back to the storyboard
Click on the ViewController that you just created
Look at the top right of the screen and there will be six little icons. Click the one third from the left and type FirstView in the first field named "Class" (see attached picture).
Note: make sure you save your FirstView.swift file or this won't work.

How about a customized Toast instead? One that is far more alluring, suits your need and requires no libraries or complex implications?
Now let us try the following bit of code
func sailAwayLabelAction(){
// here creating a rectangle with certain dimensions you can easily manipulate
let rect = CGRect(origin: CGPoint(x: self.view.frame.size.width/2 - 150,y :self.view.frame.size.height-100), size: CGSize(width: 300, height: 35))
//here creating and manipulating the attributes of your text, i.e color,alignment etc..
let toastLabel = UILabel(frame: rect)
toastLabel.backgroundColor = UIColor.orange
toastLabel.textColor = UIColor.white
toastLabel.textAlignment = NSTextAlignment.center;
toastLabel.text = "This is my customized Toast !"
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
//first pop the toast into our view
self.view.addSubview(toastLabel)
//then after 1 sec + 1 sec delay, animate the entire toastLabel out.
UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
})
}
Whenever you activate the previous function, it should render something similar to this,

try this please, through this you can get top controller of your app and then you can add toast on top controller
let win:UIWindow = UIApplication.shared.delegate!.window!!
win.currentViewController()?.view

Related

Swift : custom segue between views embedded in a navigation controller

I am still really at the beginning of learning swift and making app. So I already apologize because my problem might be really obvious but I couldn't fix it with every research made for few days. I made a small app with few views embedded in a navigation controller. It works well when I use default segues (show or present modally). But I wanted to improve it by making and using a custom segue. I made the class and used it between views embedded in the NavigationVC. Then it doesn't work. When I press button in the view nothing happen. The problem do not seems to come from the custom segue because it works well when used between view not embedded in NVC. So it might be a more fundamental problem of using custom segue within NVC. Is that not possible ? Or maybe the code may be modified for views within navigation stack. Here the custom segue :
class CustomSegueRotation : UIStoryboardSegue {
override func perform() {
let initialViewController = self.source.view
let destinationViewController = self.destination.view
let rotation = CAKeyframeAnimation (keyPath: "transform.rotation.y")
rotation.values = [0, CGFloat.pi]
rotation.autoreverses = false
initialViewController?.addSubview(destinationViewController!)
UIView.animate(withDuration: 0.3, delay: 0.05, options: .curveEaseInOut, animations: {
initialViewController?.layer.add(rotation, forKey: nil)
}, completion: nil)
}}
Thank you very much for the help.
Have you tried supplying a custom UINavigationControllerDelegate that supplies the animation you wish to use for transitions?
https://developer.apple.com/documentation/uikit/uinavigationcontrollerdelegate/1621846-navigationcontroller
You would want to implement the protocol UIViewControllerAnimatedTransitioning https://developer.apple.com/documentation/uikit/uiviewcontrolleranimatedtransitioning to describe your animations.
Then return this implementation from the delegate method I mentioned above. Finally, set the delegate on your nav controller to an instance of the custom nav controller delegate.

Snapshot of screen shows toolbar on device but not on simulator

I have a toolbar that's instantiated on viewDidLoad on top of a webkit. When I take a snapshot on the simulator, the toolbar is missing which is what I would like. When built on the device, the toolbar is there.
I tried to hide the toolbar with:
toolbar.isHidden = true
but the application crashes with toolbar being nil. If I change it to:
toolbar?.isHidden = true
It still shows up considering it still thinks it's nil.
The toolbar is set up on viewDidLoad by calling another function:
var toolbar : UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
setUpToolBar()
}
func setUpToolBar() {
let saveButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(takeScreenshot))
...
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 300, width: 200, height: 50))
toolbar.setItems([saveButton,flexibleSpaceFillerLeft,userAgentButton,flexibleSpaceFillerRight,doneButton], animated: true)
view.addSubview(toolbar)
}
The code for my snapshot is below. This is where I tried to hide the toolbar before taking the snapshot.
#objc func takeScreenshot() {
webView.takeSnapshot(with: nil, completionHandler: { (image,error) in
if let image = image {
self.screenshotOfWindow = image
self.showScreenshotEffect()
self.saveAllData()
} else {
print (error?.localizedDescription as Any)
}
})
}
Here's the screen I need to take a screenshot of:
The red box in the screenshot is the bar that I need to disappear from the screenshot.
I'd like to be able to take the screenshot without the bottom bar in view. As stated before, this works in the simulator, but the device always shows the bar. There's also a "navigation controller" gap at the top of the screenshot since the top bar covers part of the screen at top, but this is just blank and something I can address later.
I just wanted to come back and answer how I solved this. The webview is embedded in a navigation controller, but I was creating the toolbar programmatically on viewDidLoad by calling a setupToolBar function I had created early on in the project. I could hide the toolbar, but it was still being captured while taking the screenshot. I commented all of that code out and used the navigation controller's toolbar instead. Now when I take the screenshot, the bottom and top bar of the navigation controller is not part of the screenshot.

Custom TabBarController with active circle

After reading a few articles about custom UITabBarControllers, I am left more confused than before I even started doing the research in the first place.
My goal is to create a custom TabBar with 3 important properties:
No text, just icons
The active icon is marked by a circle filled with a color behind it, and therefore needs a different icon color
Here's what I am trying to achieve:
I've been able to remove the text and center the icon by following another StackOverflow answer (Remove tab bar item text, show only image), although the solution seems like a hack to me.
How would I go about creating a circle behind the item and change the active item's color?
Also, would someone mind explaining the difference between the XCode inspector sections "Tab Bar Item" and "Bar Item", which appear directly under each other?
The first step is simple: leaving the title property of the UITabbarItem empty should hide the label.
Your second step can actually be broken down into two steps: changing the color of the icon and adding a circle behind it.
The first step here is simple again: you can set a different icon to use for the currently selected ViewController (I use Storyboards, this process is pretty straightforward). What you'd do is add a white version of the icon to be shown when that menu option is selected.
The final step is displaying the circle. To do this, we'll need the following information:
Which item is currently selected?
What is the position of the icon on the screen?
The first of these two is pretty easy to find out, but the second poses a problem: the icons in a UITabBar aren't spaced around the screen equally, so we can't just divide the width of the tabbar by the amount of items in it, and then take half of that to find the center of the icons. Instead, we will subclass UITabBarController.
Note: the tabBar property of a UITabBarController does have a .selectionIndicatorImage property. You can assign an image to this and it will be shown behind your icon. However, you can't easily control the placement of this image, and that is why we still resort to subclassing UITabBarController.
class CircledTabBarController: UITabBarController {
var circle: UIView?
override func viewDidLoad() {
super.viewDidLoad()
let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: (tabBar.frame.width / numberOfItems) - 20, height: tabBar.frame.height)
circle = UIView(frame: CGRect(x: 0, y: 0, width: tabBarItemSize.height, height: tabBarItemSize.height))
circle?.backgroundColor = .darkGray
circle?.layer.cornerRadius = circle!.frame.width/2
circle?.alpha = 0
tabBar.addSubview(circle!)
tabBar.sendSubview(toBack: circle!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let index = -(tabBar.items?.index(of: tabBar.selectedItem!)?.distance(to: 0))!
let frame = frameForTabAtIndex(index: index)
circle?.center.x = frame.origin.x + frame.width/2
circle?.alpha = 1
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let index = -(tabBar.items?.index(of: item)?.distance(to: 0))!
let frame = frameForTabAtIndex(index: index)
self.circle?.center.x = frame.origin.x + frame.width/2
}
func frameForTabAtIndex(index: Int) -> CGRect {
var frames = tabBar.subviews.compactMap { (view:UIView) -> CGRect? in
if let view = view as? UIControl {
for item in view.subviews {
if let image = item as? UIImageView {
return image.superview!.convert(image.frame, to: tabBar)
}
}
return view.frame
}
return nil
}
frames.sort { $0.origin.x < $1.origin.x }
if frames.count > index {
return frames[index]
}
return frames.last ?? CGRect.zero
}
}
Now use this subclass of UITabBarController instead of the base class.
So why this approach over simply changing the icon to a circled one? Because you can do many different things with this. I wrote an article about animating the UITabBarController in a similar manner, and if you like, you can easily use above implementation to add animation to yours too.
The easiest and actually cleanest way to do it is to design your icons and import them as images to the .xcassets folder. Then you can just set the different icons for the different states for each of the viewControllers with:
ViewController.tabBarItem = UITabBarItem(title: "", image: yourImage.withRenderingMode(.alwaysOriginal), selectedImage: yourImage)
your selected image will be the one with the circle and the image will be without. It is way easier than manipulating the images in xcode and it is also less expensive since the compiler only has to render the images and doesn't have to manipulate them.
About the other question UIBarItem is
An abstract superclass for items that can be added to a bar that appears at the bottom of the screen.
UITabBarItem is a subclass of UIBarItem to provide extra funtionality.

swift iMessage style keyboard input

i am trying to implement an iMessage style keyboard input with a textview that sits at the bottom of the screen then slides up with the keyboard when you touch the textView, then is docked to the top of the keyboard.
I found MessageComposerView which is exactly what I want. Unfortunately I cannot get it working ( I am using swift).
below is my code:
import UIKit
class CommentsViewController: UIViewController, MessageComposerViewDelegate {
var messageComposerView: MessageComposerView!
override func viewDidLoad() {
super.viewDidLoad()
let defaultWidth = view.frame.size.width
let defaultHeight = CGFloat(54.0)
let subviewFrame = CGRect(x: 0, y: view.frame.height - defaultHeight, width: defaultWidth, height: defaultHeight)
messageComposerView = MessageComposerView(frame: subviewFrame) as MessageComposerView
view.addSubview(messageComposerView)
}
func messageComposerSendMessageClickedWithMessage(message: String!) {
}
}
however it does not show up. Ive printed the view and its frame is correct, its just that there is nothing there for some reason. Everything looks like it should be working. Does anyone see anything wrong with my current implementation?
Try PHFComposeBarView Library (https://github.com/fphilipe/PHFComposeBarView), it's a exact copy of the iMessage composer bar that can be used in C & Swift from storyboard or code
Code Example : https://github.com/liveminds/SwiftPHFComposeBarTest
Storyboard Example : https://github.com/liveminds/SwiftPHFComposeBarTest/tree/storyboard-managed
To add the bar to your view:
drag a new UIView on your UIViewcontroller, assign "PHFComposeBarView" class to UIView
Add an outlet of the UIView to your Viewcontroller's class
add "PHFComposeBarViewDelegate" to your Viewcontroller's class
assign UIView Delegate in viewdidload() : self.composerBarOutlet.delegate = self
Set the composer bar to appear as inputAccessoryView above the keyboard:
override var inputAccessoryView: UIView {
composerBar.removeFromSuperview()
return composerBar
}
Style your Bar(example):
composerBar.utilityButtonImage = UIImage(named: "fullStar")!
composerBar.buttonTitle = "Submit"
composerBar.maxCharCount = 200
composerBar.maxLinesCount = 5
composerBar.alpha = 1.0
composerBar.buttonTintColor = AppConfig.BLUECOLOR
composerBar.placeholder = "What do you think about this product?"
Try following this example by Andrew Bancroft Send Text Message In-App – Using MFMessageComposeViewController with Swift. His example provides a nice walkthrough using Swift and includes sample code on GitHub.
Just going from the code snippet included in your post, it looks like you need to import Foundation, import MessageUI, conform to the MFMessageComposeViewControllerDelegate protocol, and implement the messageComposeViewController protocol method. All of this is covered in Andrew's blog post. This should give you what you're looking for.
Have you find the answer yet?
I use the same Framework however I believe you need to set up the delegate to self. IN my case it fails though I dont know why but it is written down in the readme github.

Add view over tableview (UITableViewController)

Situation: I've got a UITableViewController loading some data asynchronously from a service. During this time I would like to place a full screen (except navigation bar) view over the table view showing my custom indicator and text.
Problem: The problem I'm facing is that when my custom view (it has a red background) is placed over the UITableView the lines of the table view are shown trough my custom view (see image below).
What I tried:
I tried to use insertBelow and above, didn't work. I also tried to do: tableview.Hidden = true, but this also hides the custom view for some reason as seen on image 2.
Image1: For some reason I can see the lines threw my view.
Image 2: Tableview + custom view gone when hidden = true used.
My code:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
UIView view = new UIView (new RectangleF (0, 0, this.TableView.Frame.Width, this.TableView.Frame.Height));
view.BackgroundColor = UIColor.Red;
this.TableView.AddSubview (view);
TableView.Source = new SessionTableViewSource ();
}
You can use self.navigationController.view as view for adding subview.
The issue is that the View of a UITableViewController is a UITableView, so you cannot add subviews to the controller on top of the table.
I'd recommend switching from a UITableViewController to a simple UIViewController that contains a UITableView. This way the controller main view is a plain UIView that contains a table, and you can add subviews to the main UIView and they will be placed on top of the table view.
You can try to add the view to the window instead of nesting it in the table view like this:
UIWindow* mainWindow = [[UIApplication sharedApplication] keyWindow];
[mainWindow addSubview: overlayview];
UIWindow* window = [[UIApplication sharedApplication].delegate.window;
[window addSubview: your-overlayview];
Swift / Storyboard Solution
Note: The code below assumes one has a custom view (ratingView in my case) that is to be presented over a UITableView.
I've read many answers to this and similar questions on SO. The other answers from these sources worked to varying degrees for me (e.g.,view loaded but not shown or not accessible,...). I am using Swift 2.0+ and I am sharing the complete solution for doing this using a UITableViewController.
Create an outlet to the Navigation Bar and the view, which you want to bring over the tableview.
//MARK:Outlets
#IBOutlet weak var navBar:UINavigationBar!
#IBOutlet var ratingView: MNGStarRating!
In my case I also wanted to animate the view over the tableview so I used a class variable to hold a reference to the inflection point and a point above the scene (off-screen).
var centerYInflection:NSLayoutConstraint!
var aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)
Then in viewDidLoad I called a function (configureRatingViewAutoLayout) which configures and adds the constraints for the new view to be animated over the tableview.
func configureRatingViewAutoLayout() {
//REQUIRED
self.navBar.superview?.addSubview(self.ratingView)
var newConstraints:[NSLayoutConstraint] = []
newConstraints.append(self.ratingView.leadingAnchor.constraintEqualToAnchor(self.view.leadingAnchor,constant: 10))
newConstraints.append(self.ratingView.trailingAnchor.constraintEqualToAnchor(self.view.trailingAnchor,constant: 10))
newConstraints.append(self.ratingView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor))
//hides the rating view above the scene
self.centerYInflection = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor, constant: self.aPointAboveScene)
//the priority must be set below 1000 if you intend to change it after it has been added to a view
self.centerYInflection.priority = 750
newConstraints.append(self.centerYInflection)
//constraints must be added to the container view of the two items
self.ratingView.superview?.addConstraints(newConstraints)
}
Nota Bene - On a UITableViewController; the self.view is the
self.tableView. They point to the same thing so I guess one could also
use the self.tableView reference above.
Sometime later... In response to a UIControl event I call this method.
#IBAction func toggleRatingView (sender:AnyObject?){
//REQUIRED
self.ratingView.superview?.layoutIfNeeded()
UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.37, initialSpringVelocity: 0.99, options: [.CurveEaseOut], animations: { () -> Void in
if CGRectContainsRect(self.view.frame, self.ratingView.frame) {
//in frame ~ animate away
//I play a sound to alert the user something is happening
self.centerYInflection.constant = self.aPointAboveScene
self.centerYInflection.priority = UILayoutPriority(950)
//I disable portions of the UI
self.disableUIElements(nil)
} else {
//out of frame ~ animate in
//I play a different sound here
self.centerYInflection.constant = 0
self.centerYInflection.priority = UILayoutPriority(950)
//I enable the UI fully
self.enableUIElements(nil)
}
//REQUIRED
self.ratingView.superview?.setNeedsLayout()
self.ratingView.superview?.layoutIfNeeded()
}) { (success) -> Void in
//do something else
}
}
These helper methods can be configured to control access to elements in your scene during the presentation of the view.
func disableUIElements(sender:AnyObject?) {
//UI
}
func enableUIElements(sender:AnyObject?) {
//UI
}
Caveats
My view is a custom view in the Storyboard (sitting outside of the
tableview but connected to the TableView Controller). The view has a
required user runtime attribute defined layer.zPosition with a Number value set to 2 (this ensures that it presents in front of the
UITableView).
One could also try playing around with bringSubviewToFront:
and sendSubviewToBack: methods if you don't want to set the zPosition
(I think zPosition is simpler to use)
Try this to hook a button at bottom of the UITableViewController
declare button as a variable:
var submitButton: UIButton!
and in viewDidLoad:
submitButton = UIButton(frame: CGRect(x: 5, y: UIScreen.main.bounds.size.height - 50, width: UIScreen.main.bounds.size.width - 10, height: 50))
submitButton.backgroundColor = UIColor.init(red: 180/255, green: 40/255, blue: 56/255, alpha: 1.0)
submitButton.setTitle("Submit", for: .normal)
submitButton.titleLabel?.font = UIFont(name: "Arial", size: 15)
submitButton.titleLabel?.textColor = .white
submitButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
submitButton.layer.cornerRadius = 5
self.view.addSubview(submitButton)
and implement this method:
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
submitButton.frame = CGRect.init(x: submitButton.frame.origin.x, y: UIScreen.main.bounds.size.height + scrollView.contentOffset.y - 50, width: submitButton.frame.width, height: submitButton.frame.height)
}
This works for me:
if let myTopView = Bundle.main.loadNibNamed("MyTopView", owner: self, options: nil)?.first as? MyTopView {
if let view = UIApplication.shared.keyWindow{
view.addSubview(myView);
myTopView.translatesAutoresizingMaskIntoConstraints = false
myTopView.topAnchor.constraint(equalTo: view.topAnchor ).isActive = true
myTopView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
myTopView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
myTopView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}