Swift 3 - custom segue crashed with UIStoryboardSegueTemplate.m:85 - crash

According to this link, I am trying to make my own custom segue.
In the initial view controller (titled: First), pressing 2 (UIButton) to segue to Second.
But the app always crashes at performSegue(withIdentifier: "customSegue", sender: self) with error: *** Assertion failure in -[UIStoryboardSegueTemplate segueWithDestinationViewController:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3599.6/UIStoryboardSegueTemplate.m:85
Here is the main storyboard:
Crash:
CustomSegue
import UIKit
class CustomSegue: UIStoryboardSegue {
override func perform() {
let sourceView = source.view!
let destView = destination.view!
let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
destView.frame = CGRect(x: 0, y: screenHeight, width: screenWidth, height: screenHeight)
let window = UIApplication.shared.keyWindow
window?.insertSubview(destView, aboveSubview: sourceView)
UIView.animate(withDuration: 0.4, animations: {
sourceView.frame = sourceView.frame.offsetBy(dx: 0.0, dy: -screenHeight)
destView.frame = destView.frame.offsetBy(dx: 0.0, dy: -screenHeight)
}) { [weak self] (finished) in
guard let strongSelf = self else { return }
strongSelf.source.present(strongSelf.destination, animated: false, completion: nil)
}
}
}
Second is just an empty View Controller:
import UIKit
class Second: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
I compare the setup in my project with the downloaded sample but cannot find the difference.
How should I fix this crash?

For those who are interested.
It took me nearly 2 days to find this: to overcome this crash, I have to specify "Module" in Storyboard - click on Segue - Attribute inspector.

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.

ios 10 Snapshotting a view that has not been rendered results in an empty snapshot

this question ask again but i dont find for ios 10
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
{
self.imagePicker.delegate = self
self.imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
self.imagePicker.allowsEditing = false
self.imagePicker.cameraCaptureMode = .photo
//self.imagePicker.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.present(self.imagePicker, animated: true, completion: nil)
self.imagePicked.isUserInteractionEnabled = true
}
else
{
print("No Camera")
}
Snapshotting a view that has not been rendered results in an empty
snapshot.Ensure your view has been rendered at least once before
snapshotting or snapshot after screen updates.
when i rotate the camera and take a shot than this error occurs.
Self Solution Working for me like charm :-) hope its helpful for all
DispatchQueue.global(qos: .userInitiated).async
{
self.present(self.imagePicker, animated: true, completion: nil)
}
I got the error
This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes...
Using DispatchQueue.main.async instead works for me.
This behavior is not limited to UIImagePickerController. Below is an example of a UIViewController which presents another UIViewController modally. In the second UIViewController, Safari is launched to present a URL, thus triggering the same error message, "Cannot snapshot view (>) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES."
I haven't yet found any way of suppressing the message, but in my app it does no harm. I think what's going on here is that some Apple code is taking a snapshot of the app's view hierarchy, but the keyboard (which is owned by a separate UIWIndow) has not been rendered before the snapshot is taken.
/* Generates the error message:
Cannot snapshot view (<UIKeyboardImpl: 0x7f82ded12ea0; frame = (0 0; 414 271); layer = <CALayer: 0x610000035e20>>) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES.
... after the "Now Tap Me, For Glory!" label is clicked
*/
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let input = UITextField()
input.placeholder = "Tap here first -- to bring up keyboard"
input.frame = CGRect(x: 10, y: 50, width: 300, height: 20)
view.addSubview(input)
let button = UIButton()
button.setTitleColor(UIColor.blue, for: .normal)
button.setTitle("Then tap here", for: .normal)
button.addTarget(self,
action: #selector(buttonPushed),
for: .touchUpInside)
button.frame = CGRect(x: 10, y: 80, width: 200, height: 20)
view.addSubview(button)
}
func buttonPushed() {
let modalVC = ModalViewController()
present(modalVC, animated: true, completion: nil)
}
}
class ModalViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
let label = UILabel()
label.text = "Now Tap Me, For Glory!"
label.frame = CGRect(x: 10, y: 50, width: 300, height: 20)
view.addSubview(label)
label.isUserInteractionEnabled = true
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(labelTapped)))
}
func labelTapped() {
UIApplication.shared.open(URL(string: "http://planetbeagle.com")!, options: [:], completionHandler: { _ in
self.dismiss(animated: true, completion: nil) })
}
}

How can I create a button with a background color for tvOS while still showing focus?

All I want to do is add a background color to a button for all states. But I want to maintain the automatic focus shadow that you get "for free" when using a system button in the tvOS storyboard. So far I haven't been able to find a combination that allows this.
Alternatively, I would also be interested in a way to programmatically add the shadow when the button is focused, but short of subclassing the button (which I haven't yet tried), I don't know how to do that either.
You can add a shadow for your custom button like this:
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
context.nextFocusedView.layer.shadowOffset = CGSizeMake(0, 10);
context.nextFocusedView.layer.shadowOpacity = 0.6;
context.nextFocusedView.layer.shadowRadius = 15;
context.nextFocusedView.layer.shadowColor = [UIColor blackColor].CGColor;
context.previouslyFocusedView.layer.shadowOpacity = 0;
}
Wasn't happy with a simple colour change, so I made a custom button subclass to look more like the default animation you get with system buttons -
class CustomButton: UIButton
{
private var initialBackgroundColour: UIColor!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
initialBackgroundColour = backgroundColor
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
coordinator.addCoordinatedAnimations(
{
if self.focused
{
self.backgroundColor = UIColor.whiteColor()
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformMakeScale(1.1, 1.1)
},
completion:
{
finished in
UIView.animateWithDuration(0.2, animations:
{
self.transform = CGAffineTransformIdentity
},
completion: nil)
})
}
else
{
self.backgroundColor = self.initialBackgroundColour
}
},
completion: nil)
}
}
Nothing too complicated, but gets the job done
Override didUpdateFocusInContext method and check if next focus view is button, if yes then customize its UI, and to set it back to orignal state check context.previousFocusedView was that button, something like below
- (void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator
{
if (context.nextFocusedView == _button)
{
// set background color
}
else if (context.previousFocusedView == _button)
{
// set background color to background
}
}
The Ultimate Solution with inspiration from SomaMan. Just subclass all your custom buttons and you Get this:
includes: on tap animation and release and drag away.
//
// CustomFocusButton.swift
//
import UIKit
class CustomFocusButton: UIButton {
let focusedScaleFactor : CGFloat = 1.2
let focusedShadowRadius : CGFloat = 10
let focusedShadowOpacity : Float = 0.25
let shadowColor = UIColor.blackColor().CGColor
let shadowOffSetFocused = CGSizeMake(0, 27)
let animationDuration = 0.2
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
coordinator.addCoordinatedAnimations({
if self.focused{
UIView.animateWithDuration(self.animationDuration, animations:{ [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.clipsToBounds = false
weakSelf.layer.shadowOpacity = weakSelf.focusedShadowOpacity
weakSelf.layer.shadowRadius = weakSelf.focusedShadowRadius
weakSelf.layer.shadowColor = weakSelf.shadowColor
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
},completion:{ [weak self] finished in
guard let weakSelf = self else {return}
if !finished{
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.clipsToBounds = false
weakSelf.layer.shadowOpacity = weakSelf.focusedShadowOpacity
weakSelf.layer.shadowRadius = weakSelf.focusedShadowRadius
weakSelf.layer.shadowColor = weakSelf.shadowColor
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
}
})
} else {
UIView.animateWithDuration(self.animationDuration, animations:{ [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.clipsToBounds = true
weakSelf.transform = CGAffineTransformIdentity
}, completion: {[weak self] finished in
guard let weakSelf = self else {return}
if !finished{
weakSelf.clipsToBounds = true
weakSelf.transform = CGAffineTransformIdentity
}
})
}
}, completion: nil)
}
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
UIView.animateWithDuration(animationDuration, animations: { [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformIdentity
weakSelf.layer.shadowOffset = CGSizeMake(0, 10);
})
}
override func pressesCancelled(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
if focused{
UIView.animateWithDuration(animationDuration, animations: { [weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
})
}
}
override func pressesEnded(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
if focused{
UIView.animateWithDuration(animationDuration, animations: {[weak self] () -> Void in
guard let weakSelf = self else {return}
weakSelf.transform = CGAffineTransformMakeScale(weakSelf.focusedScaleFactor, weakSelf.focusedScaleFactor)
weakSelf.layer.shadowOffset = weakSelf.shadowOffSetFocused
})
}
}
}
I've found something better:
-(void)didUpdateFocusInContext:(UIFocusUpdateContext *)context withAnimationCoordinator:(UIFocusAnimationCoordinator *)coordinator {
[coordinator addCoordinatedAnimations:^{
if (self.focused) {
self.backgroundColor = [UIColor whiteColor];
}
else {
self.backgroundColor = [UIColor clearColor];
}
} completion:nil];
}
Swift 4 /tvOS11 and better:
Set the ButtonType in the Interface Builder button properties to "Plain".
Add this private extension to your class:
private extension UIImage {
static func imageWithColor(color: UIColor, size: CGSize) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Then in your connected IBOutlet set the background image for the focused state of the button:
#IBOutlet weak var myButton: UIButton! {
didSet {
let backgroundImageSelected = UIImage.imageWithColor(color: .red, size: myButton.bounds.size)
myButton.setBackgroundImage(backgroundImageSelected, for: .focused)
}
}
You can use the UIButton method setBackgroundImage(image: UIImage?, forState state: UIControlState) and pass through an image that is a flat color and the state .Normal.
This image can easily be created programatically from a UIColor and a size of 1x1:
func getImageWithColor(color: UIColor, size: CGSize) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
You can set the background image in storyboard to an image that contains the color you would like

PDF Generation Swift

I'm trying to generate a pdf using swift. The following code compiles without error, however, the "xp.pdf" document is never created. Your help is much appreciated.
import UIKit
import Foundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func generatePDF(sender: AnyObject) {
let pageSize:CGSize = CGSizeMake (850, 1100)
let fileName: NSString = "xp.pdf"
let path:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentDirectory: AnyObject = path.objectAtIndex(0)
let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName)
generatePDFs(pdfPathWithFileName)
}
func generatePDFs(filePath: String) {
UIGraphicsBeginPDFContextToFile(filePath, CGRectZero, nil)
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 850, 1100), nil)
drawBackground()
UIGraphicsEndPDFContext()
}
func drawBackground () {
let context:CGContextRef = UIGraphicsGetCurrentContext()
let rect:CGRect = CGRectMake(0, 0, 850, 1100)
CGContextSetFillColorWithColor(context, UIColor.greenColor().CGColor)
CGContextFillRect(context, rect)
}
Do you have a pdfkit in the place?
PSPDFKit works pretty well from what I understand. You just need to download it from pspdfkit.com, then drag and drop the PSPDFKit.framework into the "Embedded Binaries" section of your app's target.
You do have to pay for it though, so theres that. I think there is a free trial for it though, so you can try it out and see if thats what you need or want.
For Xcode 7 (swift 2.0) I had to make the following changes to get it to work:
replace:
let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName)
with:
let pdfPathWithFileName = documentDirectory.stringByAppendingPathComponent(fileName as String)
and unwrap the UIGraphicsGetCurrentContext():
let context:CGContextRef = UIGraphicsGetCurrentContext()!
and also you can remove:
let pageSize:CGSize = CGSizeMake (850, 1100)
because you never use pageSize

Switch container view dynamically

I'm using a storyboard container view. So I have a view controller containing a container view. I have a second, smaller view in the storyboard, which is embedded in that container via an embed segue. So far so good.
Now I would like to be able to switch the contents of that container view dynamically, when the user taps a button. The button will be on the main, larger, view. I have made another view controller of the same smaller size, and given it a different storyboard ID.
However, I can't work out how to code the switch. I can only create a single embed segue for that container.
Any help gratefully received.
You need to use the custom container view controller api to do the switching of the controllers. The following code shows one way to do that. In this project I had a segmented control in the main view controller (the one with the container view) that switches beetween the two controllers. initialVC is the controller that's embedded in IB, and substituteVC is the one I'm switching to. The property, container, is an IBOutlet to the container view.
- (void)viewDidLoad {
[super viewDidLoad];
self.initialVC = self.childViewControllers.lastObject;
self.substituteVC = [self.storyboard instantiateViewControllerWithIdentifier:#"Substitute"];
self.currentVC = self.initialVC;
}
-(IBAction)switchControllers:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0:
if (self.currentVC == self.substituteVC) {
[self addChildViewController:self.initialVC];
self.initialVC.view.frame = self.container.bounds;
[self moveToNewController:self.initialVC];
}
break;
case 1:
if (self.currentVC == self.initialVC) {
[self addChildViewController:self.substituteVC];
self.substituteVC.view.frame = self.container.bounds;
[self moveToNewController:self.substituteVC];
}
break;
default:
break;
}
}
-(void)moveToNewController:(UIViewController *) newController {
[self.currentVC willMoveToParentViewController:nil];
[self transitionFromViewController:self.currentVC toViewController:newController duration:.6 options:UIViewAnimationOptionTransitionFlipFromLeft animations:nil
completion:^(BOOL finished) {
[self.currentVC removeFromParentViewController];
[newController didMoveToParentViewController:self];
self.currentVC = newController;
}];
}
After Edit:
If you want to go to the new controller with no animation, you can do it like this (this substitutes for the code that I had under case 1).
[self addChildViewController:self.substituteVC];
[self.substituteVC didMoveToParentViewController:self];
self.substituteVC.view.frame = self.container.bounds;
[self.container addSubview:self.substituteVC.view];
[self.currentVC removeFromParentViewController];
rdelmar's answer converted to Swift syntax
override func viewDidLoad() {
super.viewDidLoad()
self.initialVC = self.childViewControllers.last
self.substituteVC = self.storyboard!.instantiateViewControllerWithIdentifier("Substitute")
self.currentVC = self.initialVC;
}
#IBAction func switchControllers(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex{
case 0:
if (self.currentVC == self.substituteVC) {
self.addChildViewController(self.initialVC)
//self.initialVC.view.frame = self.containerView.bounds
moveToNewController(self.initialVC)
}
case 1:
if (self.currentVC == self.initialVC) {
self.addChildViewController(self.substituteVC)
//self.substituteVC.view.frame = self.containerView.bounds
moveToNewController(self.substituteVC)
}
default:
break;
}
}
func moveToNewController(newController : UIViewController){
self.currentVC.willMoveToParentViewController(nil)
self.transitionFromViewController(
self.currentVC!,
toViewController: newController,
duration: 0.2,
options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: nil,
completion: { finished in
self.currentVC.removeFromParentViewController()
newController.didMoveToParentViewController(self)
self.currentVC = newController
})
}
If you deal with more than 2 child view controllers it's a good idea to store them in array. Also, you'll need to apply constraints every time you add a new subview to the container view. Here's a modified version of the accepted answer (using Swift 2 syntax):
import UIKit
class FooBarViewController: UIViewController
{
// MARK: - IBOutlets
#IBOutlet weak var containerView: UIView!
// MARK: - Properties
var vcs = [UIViewController]()
var currentVC: UIViewController!
// MARK: - ViewController Lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
vcs.append(childViewControllers.last!)
vcs.append(storyboard!.instantiateViewControllerWithIdentifier("FooViewControler"))
vcs.append(storyboard!.instantiateViewControllerWithIdentifier("BarViewController"))
currentVC = vcs[0]
for vc in vcs {
vc.view.frame = containerView.bounds
}
}
// MARK: - Methods
func switchToViewController(targetVC: UIViewController)
{
addChildViewController(targetVC)
currentVC.willMoveToParentViewController(nil)
transitionFromViewController(
currentVC,
toViewController: targetVC,
duration: 0.0, // 0.3
options: .TransitionNone, // .TransitionCrossDissolve,
animations: nil,
completion: { finished in
self.currentVC.removeFromParentViewController()
targetVC.didMoveToParentViewController(self)
self.currentVC = targetVC
self.applyConstraints()
})
}
func applyConstraints()
{
let viewsDict = ["newSubview": currentVC.view]
currentVC.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("H:|[newSubview]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil,
views: viewsDict))
containerView.addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:|[newSubview]|",
options: NSLayoutFormatOptions(rawValue: 0),
metrics: nil, views:
viewsDict))
}
// MARK: - IBActions
#IBAction func switchControllers(sender: UISegmentedControl)
{
let i = sender.selectedSegmentIndex
if currentVC != vcs[i] {
self.addChildViewController(vcs[i])
switchToViewController(vcs[i])
}
}
}