How do you set canBecomeFocused for a custom view - objective-c

I am making an application for tvOS. I have a view that contains a UIButton and a custom UIView that contains a couple other custom views. The simulator is only able to highlight the UIButton and not the custom view.
According to the Building Apple TV Apps Docs:
If your custom view needs to be focusable, override canBecomeFocused to return YES (by default, it returns NO).
According to the canBecomeFocused Docs:
canBecomeFocused will return
YES if the view can become focused; NO otherwise.
However, attempting to assign YES to canBecomeFocused by doing this:
self.customView.canBecomeFocused = YES;
Gives this error:
No setter method 'setCanBecomeFocused:' for assignment to property
How do I accomplish this?

It looks like UIView declares the function/property.
Have you tried overriding the function like so?
Swift
override func canBecomeFocused() -> Bool {
return true
}
Objective-C
- (BOOL)canBecomeFocused {
return YES;
}
I haven't tried this, but it may work for you.

Besides of overriding the canBecomeFocused method in your custom view:
override func canBecomeFocused() -> Bool {
return true
}
Make sure your custom view userInteractionEnabled is true. This is the complete list to be sure your view can be focused:
Why Is This View Not Focusable?
There are a number of reasons a view that is expected to be focusable may not be, including (but not limited to):
The view’s canBecomeFocused method returns NO.
The view’s hidden
property has a value of YES.
The view’s alpha property has a value of 0.
The view’s user interaction is disabled.
The view is obscured by another view on top of it.

Above answers are not enough this my customView code block.
Swift
import UIKit
class Focus: UIView {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override func canBecomeFocused() -> Bool {
return true
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) {
if context.previouslyFocusedView === self {
UIView.animateWithDuration(0.1, animations: { () -> Void in
context.previouslyFocusedView?.transform = CGAffineTransformMakeScale(1.0, 1.0)
})
}
if context.nextFocusedView === self {
UIView.animateWithDuration(0.1, animations: { () -> Void in
context.nextFocusedView?.transform = CGAffineTransformMakeScale(1.4, 1.4)
})
}
}
}

Related

inputAccessoryView Dismiss Keyboard

I have a textView docked to the bottom of the view. However, the keyboard wont dismiss when the user taps outside the commentTextView.
Current Attempt:
import UIKit
class CommentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var commentBar: UIView!
#IBOutlet var commentTextField: UITextField!
override var inputAccessoryView: UIView {
return commentBar
}
override func canBecomeFirstResponder() -> Bool {
commentBar.removeFromSuperview()
return true
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
commentTextField.resignFirstResponder()
}
According to Apple's documentation, the keyboard won't dismiss by default when the user taps outside of the UITextView. You do need to handle this programmatically when you want to dismiss the keyboard by calling commentTextField.resignFirstResponder().
UITextFiled Reference about Managing the Keyboard
It is your application’s responsibility to dismiss the keyboard at the time of your choosing. You might dismiss the keyboard in response to a specific user action, such as the user tapping a particular button in your user interface. To dismiss the keyboard, send the resignFirstResponder message to the text view that is currently the first responder.
There are many ways for a user may hide the keyboard.
Situation 1: one is when the user tap on the Return button on the keyboard. This is exactly what your following function is for:
func textFieldShouldReturn(textField: UITextField!) -> Bool {
commentTextField.resignFirstResponder();
return true;
}
But the major problem is that the above function won't get called because you forget to set the UITextFieldDelegate. In short, you need to change the class definition to the following:
class CommentsViewController: UIViewController, UITextFieldDelegate /*Add This*/, UITableViewDelegate, UITableViewDataSource {
// ....
}
You will also have to set the delete either in the storyboard or by code. It is the same as setting the UITableViewDelegate and UITableViewDataSource. By the following is an example of setting it in code:
override func viewDidLoad() {
super.viewDidLoad()
commentTextField.delegate = self;
}
Situation 2: when user tap on the table view. You can simply implement the following UITableViewDelegate and it should work.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
commentTextField.resignFirstResponder();
}
Situation 3: when the user tap on a background view. This is what the following code is for. However, this function will not get called when user is tap on the table view. If you want to know why, please refer to the responder chain for more details.
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// self.view.endEditing(true); // This line is redundant.
commentTextField.resignFirstResponder()
}
To sum up, there is no quick and easy way to dismiss the keyboard say "when the user taps outside the textView". You do need to handle all different situations according to your need.
Try to set keyboard resign on your tableview as shown in figure.
check any
-dismiss on drag
-dismiss interactively
did you add Table View?
if yes, tableViewCell will receive the touch event instead of controller.view.
you could override the method in custom tableView cell:
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if (xxTextField.isFirstResponder){
return viewController.view
}
return self
}
Another way you can try,maybe it work:
add UITapGestureRecognizer to controller.view.
When you say "outside of my UITextField", I'm guessing you mean "on another element in my view". I can see that you have a UITableViewDelegate and UITableViewDataSource, which tells me you have a tableView inside CommentsViewController.
You can implement the function func tableView(_ tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) and there you can resign the keyboard by calling commentTextField.resignFirstResponder()
First, your view controller needs to implement UITextFieldDelegate, so add that. Then, set your view controller as the delegate for the textfield
then add these methods. The first one will resignFirstResponder when your text field ends editing. The second resigns when you hit return. The last forces your textfield to end editing when you tap the background.
func textFieldDidEndEditing(textField: UITextField) {
textField.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.commentTextField.endEditing(true)
}
Modify
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true);
commentTextField.resignFirstResponder()
}
To
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
super.touchesBegan(touches, withEvent: event)
self.view.endEditing(true)
}
It should do the job.
Try this
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true);
commentTextField.resignFirstResponder()
}

How to create background for NSView when using storyboards with OS X

I know how I may be able to do this programmatically. I know that when creating storyboards for iOS it's very easy and is right there in the attributes inspector. However when creating storyboards for OS X, I don't see it for any of my view controllers or the view underneath it in Xcode 6.1.1
How can I change the background of the view without having to create a view controller associated with it. My application has a lot of views that are simple, but the background changes colour from one view to the next.
Here is another way to achieve the same effect.
Add NSBox under your NSView and adjust NSBox's frame as the same with the NSView.
Change Title position to None, Box type to Custom, Border Type to None
This is the screenshot:
And than add your NSView, NSButton, NSTextField or whatever as a subview of NSBox.
This is the result:
You shouldn't need a new viewController to change the background of an NSView. If you aren't subclassing NSView, then you can simply call:
myView.wantsLayer = true
myView.layer!.backgroundColor = CGColorGetConstantColor(kCGColorBlack)
I'm not sure if you can do it strictly in the storyboard, though you can likely set the wantsLayer = true in storyboard using the User Defined Runtime Attributes.
You can change a NSView's background color in the storyboard if you subclass NSView and assign the subclass to your view:
Using this subclass implementation:
import Cocoa
class ViewWithBackgroundColor : NSView {
#IBInspectable var backgroundColor: NSColor? {
get {
guard let layer = layer, backgroundColor = layer.backgroundColor else { return nil }
return NSColor(CGColor: backgroundColor)
}
set {
wantsLayer = true
layer?.backgroundColor = newValue?.CGColor
}
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
The background color isn't shown at design time but at run-time.
Maybe somebody got an idea how to also update the view at design time (preferably without overriding the draw method).

How do you pass a generic class type in a recursive extension (category) function in Swift?

I want to programmatically change the text color of a specific class type (UILabel, UITextField, etc.) for ALL subviews (not just it's direct children, but also the children of that child and so on) .
I created an extension to UIView that recursively visits all of it's subviews and their subviews. It's currently hard coded to change the color for a single type (UILabel).
Here's the code I've got:
import UIKit
extension UIView {
func setLabelTextColor(color: UIColor) {
for subview in self.subviews {
// Visit any subviews of the current subview (this is the recursive part)
subview.setLabelTextColor(color)
// Is this a label? If so, change it's text color.
if let label = subview as? UILabel { <-- I WANT TO PASS THIS CLASS
label.textColor = color
}
}
}
}
class OptimusPrimeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.setLabelTextColor(UIColor.blueColor())
}
}
How do I use generics in Swift to pass the class type (like UITextField instead of UILabel) so I can specify which class' text color I want to change? Maybe there's some block(closure) magic that could do the same thing?
So instead of:
self.view.setLabelTextColor(UIColor.blueColor())
I'd have something like:
self.view.setTextColor(UIColor.blueColor(), forClassType: UITextField.self)
You can define a generic type T in the function definition like this:
extension UIView {
func setTextColor<T: UIView>(color: UIColor, forClassType _: T.Type) {
for subview in self.subviews as [UIView] {
subview.setTextColor(color, forClassType: T.self)
if let view = subview as? T {
view.textColor = color
}
}
}
}
However, textColor is not a property of all UIViews, so you need to go a step further. One solution is to define a protocol with a textColor property, then declare protocol conformance for UILabel, UITextField and any other classes you want to use with this function. If the class doesn't already define the textColor property, you'll need to add it in the extension.
So here's the complete code:
protocol HasTextColor {
var textColor: UIColor! { get set }
}
extension UILabel: HasTextColor {}
extension UITextField: HasTextColor {}
extension UIView {
func setTextColor<T: UIView where T: HasTextColor>(color: UIColor, forClassType _: T.Type) {
for subview in self.subviews as [UIView] {
subview.setTextColor(color, forClassType: T.self)
if let view = subview as? T {
view.textColor = color
}
}
}
}
You would call this function exactly as you suggested:
self.view.setTextColor(UIColor.blueColor(), forClassType: UITextField.self)
I think I figured out a way to do this without having to use a protocol and having to explicitly conform every class to that protocol so they can use this function.
Instead It uses introspection with NSObject to see if the view is the right type and has that property. This way I can use it with anything that has textColor and don't have to add as much code.
func setGlobalTextColor<T: NSObject>(color: UIColor, forClassType: T.Type) {
for subview in self.subviews as [UIView]{
// Visit every child before applying changes
subview.setGlobalTextColor(color, forClassType: T.self)
// Only change text color for the class we called the function with
if subview.isMemberOfClass(T) {
// Sanity check to make sure we only set if class has this property
if subview.respondsToSelector(Selector("textColor")) {
// Use Key Value Coding to set the textColor
subview.setValue(color, forKey: "textColor")
}
}
}
}
So you can call it with different classes that have a UIColor textColor property:
self.view.setTextColor(UIColor.blueColor(), forClassType: UILabel.self)
self.view.setTextColor(UIColor.redColor(), forClassType: UITextField.self)

NSStoryboardSegue sample code (Yosemite Storyboard)

OS X Yosemite introduced NSStoryboardSegue
“A storyboard segue specifies a transition or containment relationship between two scenes in a storyboard…”
Update:
• If I attempt to use a NSStoryboardSegue subclass in a Storyboard with Yosemite., it crashes with SIGABRT.
• If I ignore segues, and manually present a view controller using a specified, custom animator for presentation and dismissal,
func presentViewController(_ viewController: NSViewController,
animator animator: NSViewControllerPresentationAnimator)
it works as expected.
This post provides additional insight: Animate custom presentation of ViewController in OS X Yosemite
Using that as a reference, here's my attempt so far:
class FadeSegue: NSStoryboardSegue {
override func perform() {
super.perform()
sourceController.presentViewController(destinationController as NSViewController,
animator: FadeTransitionAnimator())
}
}
class FadeTransitionAnimator: NSObject, NSViewControllerPresentationAnimator {
func animatePresentationOfViewController(toViewController: NSViewController, fromViewController: NSViewController) {
toViewController.view.wantsLayer = true
toViewController.view.layerContentsRedrawPolicy = .OnSetNeedsDisplay
toViewController.view.alphaValue = 0
fromViewController.view.addSubview(toViewController.view)
toViewController.view.frame = fromViewController.view.frame
NSAnimationContext.runAnimationGroup({ context in
context.duration = 2
toViewController.view.animator().alphaValue = 1
}, completionHandler: nil)
}
func animateDismissalOfViewController(viewController: NSViewController, fromViewController: NSViewController) {
viewController.view.wantsLayer = true
viewController.view.layerContentsRedrawPolicy = .OnSetNeedsDisplay
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 2
viewController.view.animator().alphaValue = 0
}, completionHandler: {
viewController.view.removeFromSuperview()
})
}
}
The problem appears to be with the Swift 'subclassing' of NSStoryboardSegue. If you implement the same functionality using Objective-C, everything works as expected. The problem is specifically with your FadeSeque class. The animator object works fine in either Objective-C or Swift.
So this:
class FadeSegue: NSStoryboardSegue {
override func perform() {
super.perform()
sourceController.presentViewController(destinationController as NSViewController,
animator: FadeTransitionAnimator())
}
}
Will work if provided as an Objective-C class:
#interface MyCustomSegue : NSStoryboardSegue
#end
#implementation FadeSegue
- (void)perform {
id animator = [[FadeTransitionAnimator alloc] init];
[self.sourceController presentViewController:self.destinationController
animator:animator];
}
#end
(I don't think you need to call super )
As this doesn't seem to be documented much anywhere, I have made a small project on github to demonstrate:
NSStoryboardSegue transitions from one NSViewController to another in the same Storyboard
NSViewController present: methods to achieve the same affect to a separate Xib-based NSViewController without using a Storyboard Segue
presentViewController:asPopoverRelativeToRect:ofView:preferredEdge:behavior:
presentViewControllerAsSheet:
presentViewControllerAsModalWindow:
presentViewController:animator:
animator and segue objects in Objective-C and Swift
edit
OK I've tracked down the EXC_BAD_ACCESS issue. Looking in the stack trace it seemed to have something to do with (Objective-C) NSString to (Swift) String conversion.
That made wonder about the identifier property of NSStoryboardSegue. This is used when setting up segues in the Storyboard, and is not so useful in Custom segues created in code. However, it turns out that if you set an identifier in the storyboard to any string value, even "", the crash disappears.
The identifier property is an NSString* in Objective-C
#property(readonly, copy) NSString *identifier
and an optional String in Swift:
var identifier: String? { get }
Note the read-only status. You can only set the identifier on initialising the object.
The designator initialiser for NSStoryboardSegue looks like this in Objective-C:
- (instancetype)initWithIdentifier:(NSString *)identifier
source:(id)sourceController
destination:(id)destinationController
and in Swift:
init(identifier identifier: String,
source sourceController: AnyObject,
destination destinationController: AnyObject)
Note the non-optional requirement in the Swift initialiser. Therein lies the problem and the crash. If you don't deliberately set an identifier in the storyboard, the Custom segue's designated initialiser will be called using a nil value for the identifier. Not a problem in Objective-C, but bad news for Swift.
The quick solution is to ensure you set an identifier string in Storyboard. For a more robust solution, it turns out that you can override the designated initialiser in your custom subclass to intercept a nil-valued string. Then you can fill it in with a default value before passing on to super's designated initialiser:
override init(identifier: String?,
source sourceController: AnyObject,
destination destinationController: AnyObject) {
var myIdentifier : String
if identifier == nil {
myIdentifier = ""
} else {
myIdentifier = identifier!
}
super.init(identifier: myIdentifier,
source: sourceController,
destination: destinationController)
}
I have updated the sample project to reflect this solution
The same issue comes to me since I forgot make Identity to the segue.
After that, my segue subclass could worked fine.
Highly recommend you take a look at the Apple documentation. If you dig into it a bit, you'll notice in the perform method, you can override animations and such:
SWIFT
func perform()
OBJECTIVE-C
- (void)perform
"You can override this method in your NSStoryboardSegue subclass to perform custom animation between the starting/containing controller and the ending/contained controller for a storyboard segue. Typically, you would use Core Animation to set up an animation from one set of views to the next. For more complex animations, you might take a snapshot image of the two view hierarchies and manipulate the images instead of the view objects.*
Regardless of how you perform the animation, you are responsible for installing the destination view controller o window controller (and its contained views) in the right place so that it can handle events. Typically, this entails calling one of the presentation methods in the NSViewController class."
What you might do as well is have a look at some of the iOS UIStoryboardSegue examples out there in the wild and you should find they're quite similar.

How to use single storyboard uiviewcontroller for multiple subclass

Let say I have a storyboard that contains UINavigationController as initial view controller. Its root view controller is subclass of UITableViewController, which is BasicViewController. It has IBAction which is connected to right navigation button of the navigation bar
From there I would like to use the storyboard as a template for other views without having to create additional storyboards. Say these views will have exactly the same interface but with root view controller of class SpecificViewController1 and SpecificViewController2 which are subclasses of BasicViewController.
Those 2 view controllers would have the same functionality and interface except for the IBAction method.
It would be like the following:
#interface BasicViewController : UITableViewController
#interface SpecificViewController1 : BasicViewController
#interface SpecificViewController2 : BasicViewController
Can I do something like that?
Can I just instantiate the storyboard of BasicViewController but have root view controller to subclass SpecificViewController1 and SpecificViewController2?
Thanks.
great question - but unfortunately only a lame answer. I don't believe that it is currently possible to do what you propose because there are no initializers in UIStoryboard that allow overriding the view controller associated with the storyboard as defined in the object details in the storyboard on initialization. It's at initialization that all the UI elements in the stoaryboard are linked up to their properties in the view controller.
It will by default initialize with the view controller that is specified in the storyboard definition.
If you are trying to gain reuse of UI elements you created in the storyboard, they still must be linked or associated to properties in which ever view controller is using them for them to be able to "tell" the view controller about events.
It's not that much of a big deal copying over a storyboard layout especially if you only need a similar design for 3 views, however if you do, you must make sure that all the previous associations are cleared, or it will get crashes when it tries to communicate to the previous view controller. You will be able to recognize them as KVO error messages in the log output.
A couple of approaches you could take:
store the UI elements in a UIView - in a xib file and instantiate it from your base class and add it as a sub view in the main view, typically self.view. Then you would simply use the storyboard layout with basically blank view controllers holding their place in the storyboard but with the correct view controller sub class assigned to them. Since they would inherit from the base, they would get that view.
create the layout in code and install it from your base view controller. Obviously this approach defeats the purpose of using the storyboard, but may be the way to go in your case. If you have other parts of the app that would benefit from the storyboard approach, it's ok to deviate here and there if appropriate. In this case, like above, you would just use bank view controllers with your subclass assigned and let the base view controller install the UI.
It would be nice if Apple came up with a way to do what you propose, but the issue of having the graphic elements pre-linked with the controller subclass would still be an issue.
have a great New Year!!
be well
The code of line we are looking for is:
object_setClass(AnyObject!, AnyClass!)
In Storyboard -> add UIViewController give it a ParentVC class name.
class ParentVC: UIViewController {
var type: Int?
override func awakeFromNib() {
if type = 0 {
object_setClass(self, ChildVC1.self)
}
if type = 1 {
object_setClass(self, ChildVC2.self)
}
}
override func viewDidLoad() { }
}
class ChildVC1: ParentVC {
override func viewDidLoad() {
super.viewDidLoad()
println(type)
// Console prints out 0
}
}
class ChildVC2: ParentVC {
override func viewDidLoad() {
super.viewDidLoad()
println(type)
// Console prints out 1
}
}
As the accepted answer states, it doesn't look like it is possible to do with storyboards.
My solution is to use Nib's - just like devs used them before storyboards. If you want to have a reusable, subclassable view controller (or even a view), my recommendation is to use Nibs.
SubclassMyViewController *myViewController = [[SubclassMyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
When you connect all your outlets to the "File Owner" in the MyViewController.xib you are NOT specifying what class the Nib should be loaded as, you are just specifying key-value pairs: "this view should be connected to this instance variable name." When calling [SubclassMyViewController alloc] initWithNibName: the initialization process specifies what view controller will be used to "control" the view you created in the nib.
It is possible to have a storyboard instantiate different subclasses of a custom view controller, though it involves a slightly unorthodox technique: overriding the alloc method for the view controller. When the custom view controller is created, the overridden alloc method in fact returns the result of running alloc on the subclass.
I should preface the answer with the proviso that, although I have tested it in various scenarios and received no errors, I can't ensure that it will cope with more complex set ups (but I see no reason why it shouldn't work). Also, I have not submitted any apps using this method, so there is the outside chance that it might be rejected by Apple's review process (though again I see no reason why it should).
For demonstration purposes, I have a subclass of UIViewController called TestViewController, which has a UILabel IBOutlet, and an IBAction. In my storyboard, I have added a view controller and amended its class to TestViewController, and hooked up the IBOutlet to a UILabel and the IBAction to a UIButton. I present the TestViewController by way of a modal segue triggered by a UIButton on the preceding viewController.
To control which class is instantiated, I have added a static variable and associated class methods so get/set the subclass to be used (I guess one could adopt other ways of determining which subclass is to be instantiated):
TestViewController.m:
#import "TestViewController.h"
#interface TestViewController ()
#end
#implementation TestViewController
static NSString *_classForStoryboard;
+(NSString *)classForStoryboard {
return [_classForStoryboard copy];
}
+(void)setClassForStoryBoard:(NSString *)classString {
if ([NSClassFromString(classString) isSubclassOfClass:[self class]]) {
_classForStoryboard = [classString copy];
} else {
NSLog(#"Warning: %# is not a subclass of %#, reverting to base class", classString, NSStringFromClass([self class]));
_classForStoryboard = nil;
}
}
+(instancetype)alloc {
if (_classForStoryboard == nil) {
return [super alloc];
} else {
if (NSClassFromString(_classForStoryboard) != [self class]) {
TestViewController *subclassedVC = [NSClassFromString(_classForStoryboard) alloc];
return subclassedVC;
} else {
return [super alloc];
}
}
}
For my test I have two subclasses of TestViewController: RedTestViewController and GreenTestViewController. The subclasses each have additional properties and each override viewDidLoad to change the background colour of the view and update the text of the UILabel IBOutlet:
RedTestViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor redColor];
self.testLabel.text = #"Set by RedTestVC";
}
GreenTestViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
self.testLabel.text = #"Set by GreenTestVC";
}
On some occasions I might want to instantiate TestViewController itself, on other occasions RedTestViewController or GreenTestViewController. In the preceding view controller, I do this at random as follows:
NSInteger vcIndex = arc4random_uniform(4);
if (vcIndex == 0) {
NSLog(#"Chose TestVC");
[TestViewController setClassForStoryBoard:#"TestViewController"];
} else if (vcIndex == 1) {
NSLog(#"Chose RedVC");
[TestViewController setClassForStoryBoard:#"RedTestViewController"];
} else if (vcIndex == 2) {
NSLog(#"Chose BlueVC");
[TestViewController setClassForStoryBoard:#"BlueTestViewController"];
} else {
NSLog(#"Chose GreenVC");
[TestViewController setClassForStoryBoard:#"GreenTestViewController"];
}
Note that the setClassForStoryBoard method checks to ensure that the class name requested is indeed a subclass of TestViewController, to avoid any mix-ups. The reference above to BlueTestViewController is there to test this functionality.
Basing particularly on nickgzzjr and Jiří Zahálka answers plus comment under the second one from CocoaBob I've prepared short generic method doing exactly what OP needs. You need only to check storyboard name and View Controllers storyboard ID
class func instantiate<T: BasicViewController>(as _: T.Type) -> T? {
let storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
guard let instance = storyboard.instantiateViewController(withIdentifier: "Identifier") as? BasicViewController else {
return nil
}
object_setClass(instance, T.self)
return instance as? T
}
Optionals are added to avoid force unwrap (swiftlint warnings), but method returns correct objects.
Also: you need to initialize properties existing only in subclass before reading them from casted objects (if subclass has those properties and BasicViewController does not). Those properties won't be initialized automatically and attempt to read them before initialization will lead to crash. Because they are there in effect of casting it's very likely that even weak variables won't be set to nil (will contain garbage).
try this, after instantiateViewControllerWithIdentifier.
- (void)setClass:(Class)c {
object_setClass(self, c);
}
like :
SubViewController *vc = [sb instantiateViewControllerWithIdentifier:#"MainViewController"];
[vc setClass:[SubViewController class]];
Although it's not strictly a subclass, you can:
option-drag the base class view controller in the Document Outline to make a copy
Move the new view controller copy to a separate place on the storyboard
Change Class to the subclass view controller in the Identity Inspector
Here's an example from a Bloc tutorial I wrote, subclassing ViewController with WhiskeyViewController:
This allows you to create subclasses of view controller subclasses in the storyboard. You can then use instantiateViewControllerWithIdentifier: to create specific subclasses.
This approach is a bit inflexible: later modifications within the storyboard to the base class controller don't propagate to the subclass. If you have a lot of subclasses you may be better off with one of the other solutions, but this will do in a pinch.
Objc_setclass method doesn't create an instance of childvc. But while popping out of childvc, deinit of childvc is being call. Since there is no memory allocated separetely for childvc, app crashes. Basecontroller has an instance , whereas child vc doesn't have.
If you are not too reliant on storyboards, you can create a separate .xib file for the controller.
Set the appropriate File's Owner and outlets to the MainViewController and override init(nibName:bundle:) in the Main VC so that its children can access the same Nib and its outlets.
Your code should look like this:
class MainViewController: UIViewController {
#IBOutlet weak var button: UIButton!
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "MainViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
button.tintColor = .red
}
}
And your Child VC will be able to reuse its parent's nib:
class ChildViewController: MainViewController {
override func viewDidLoad() {
super.viewDidLoad()
button.tintColor = .blue
}
}
There is a simple, obvious, everyday solution.
Simply put the existing storyboard/controller inside the new storyobard/controller. I.E. as a container view.
This is the exactly analogous concept to "subclassing", for, view controllers.
Everything works exactly as in a subclass.
Just as you commonly put a view subview inside another view, naturally you commonly put a view controller inside another view controller.
How else can could you do it?
It's a basic part of iOS, as simple as the concept "subview".
It's this easy ...
/*
Search screen is just a modification of our List screen.
*/
import UIKit
class Search: UIViewController {
var list: List!
override func viewDidLoad() {
super.viewDidLoad()
list = (_sb("List") as! List
addChild(list)
view.addSubview(list.view)
list.view.bindEdgesToSuperview()
list.didMove(toParent: self)
}
}
You now obviously have list to do whatever you want with
list.mode = .blah
list.tableview.reloadData()
list.heading = 'Search!'
list.searchBar.isHidden = false
etc etc.
Container views are "just like" subclassing in the same way that "subviews" are "just like" subclassing.
Of course obviously, you can't "sublcass a layout" - what would that even mean?
("Subclassing" relates to OO software and has no connection to "layouts".)
Obviously when you want to re-use a view, you just subview it inside another view.
When you want to re-use a controller layout, you just container view it inside another controller.
This is like the most basic mechanism of iOS!!
Note - for years now it's been trivial to dynamically load another view controller as a container view. Explained in the last section: https://stackoverflow.com/a/23403979/294884
Note - "_sb" is just an obvious macro we use to save typing,
func _sb(_ s: String)->UIViewController {
// by convention, for a screen "SomeScreen.storyboard" the
// storyboardID must be SomeScreenID
return UIStoryboard(name: s, bundle: nil)
.instantiateViewController(withIdentifier: s + "ID")
}
Thanks for #Jiří Zahálka's inspiring answer, I replied my solution 4 years ago here, but #Sayka suggested me to post it as an answer, so here it is.
In my projects, normally, if I'm using Storyboard for a UIViewController subclass, I always prepare a static method called instantiate() in that subclass, to create an instance from Storyboard easily. So for solve OP's question, if we want to share the same Storyboard for different subclasses, we can simply setClass() to that instance before returning it.
class func instantiate() -> SubClass {
let instance = (UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SuperClass") as? SuperClass)!
object_setClass(instance, SubClass.self)
return (instance as? SubClass)!
}
Here is a Swift solution which does not rely on Objective-C class swapping hacks.
It uses instantiateViewController(identifier:creator:) (iOS 13+).
I assume you have the view controller in a storyboard, with identifier template. The class assigned to the view controller in the storyboard should be the superclass:
let storyboard = UIStoryboard(name: "main", bundle: nil)
let viewController = storyboard.instantiateViewController(identifier: "template") { coder in
// The coder provides access to the storyboard data.
// We can now init the preferred UIViewController subclass.
if useSubclass {
return SpecialViewController(coder: coder)
} else {
return BaseViewController(coder: coder)
}
}
Here is the documentation
Probably most flexible way is to use reusable views.
(Create a View in separate XIB file or Container view and add it to each subclass view controller scene in storyboard)
Taking answers from here and there, I came up with this neat solution.
Create a parent view controller with this function.
class ParentViewController: UIViewController {
func convert<T: ParentViewController>(to _: T.Type) {
object_setClass(self, T.self)
}
}
This allows the compiler to ensure that the child view controller inherits from the parent view controller.
Then whenever you want to segue to this controller using a sub class you can do:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let parentViewController = segue.destination as? ParentViewController {
ParentViewController.convert(to: ChildViewController.self)
}
}
The cool part is that you can add a storyboard reference to itself, and then keep calling the "next" child view controller.
Cocoabob's comment from Jiří Zahálka answer helped me to get this solution and it worked well.
func openChildA() {
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let parentController = storyboard
.instantiateViewController(withIdentifier: "ParentStoryboardID")
as! ParentClass;
object_setClass(parentController, ChildA.self)
self.present(parentController, animated: true, completion: nil);
}
It is plain simple. Just define the BaseViewController in a xib and then use it like this:
let baseVC: BaseViewController = BaseViewController(nibName: "BaseViewController", bundle: nil)
let subclassVC: ChildViewController = ChildViewController(nibName: "BaseViewController", bundle: nil)
To make is simple you can extract the identifier to a field and the loading to a method like:
public static var baseNibIdentifier: String {
return "BaseViewController"
}
public static func loadFromBaseNib<T>() -> T where T : UIViewController {
return T(nibName: self.baseNibIdentifier, bundle: nil)
}
Then you can use it like this:
let baseVC: BaseViewController = BaseViewController.loadFromBaseNib()
let subclassVC: ChildViewController = ChildViewController.loadFromBaseNib()