NSBox is not showing methods to add content in it (Swift) - objective-c

I would need to add some contents inside a NSBox, an Image and some text.
To do that I use the methods of NSBox class and call them on the object.
I created an IBOutlet:
#IBOutlet weak var theBox: NSBox!
and I also have a button, once I click it, the box will be filled with text (NSTextField):
#IBAction func filler(sender: AnyObject)
{
var label: NSTextField! = NSTextField() //Initialized a label to put it in the box
label.stringValue = "My text hey hey hey!"
theBox.setContentView(label) //I GET AN ERROR MESSAGE HERE
}
to add the content I used .setContentViewbut this method is not callable on the object theBoxand I don't know why I am wrong. Look at the documentation. The method exists and it is callable on the NSBox objects.
I'm new with swift and OSX development. Any Idea?

In Swift, you don't call the set methods for properties, you just assign to them directly:
theBox.contentView = label

Related

Swift: Set properties to an Extension of IBOutletCollection containing UIButtons

How can I set properties to an "extension" of an "IBOutletCollection" containing "UIButtons"? I am trying to do this in a similar way that one can do with an extension UIButton, that does not seem to extend to a collection of UIButtons. I hope to be as thorough and clear as possible.
Although there are similar questions:
1.Change the color of UIButton in IBOutletCollection
2.Set Individual Title of UIButtons in IBOutletCollection
...and numourous others. I still am not grasping how to do this, and can really use help that any of you can provide.
Here is what I have gathered so far:
An IBOutletCollection is always an NSArray.
Use a for-in-loop to iterate through the array’s content.
Here is my code example: ( I have tried replacing where “Array” is with: “NSArray” & “Collection” with “Collection” working similar to “Array”)
//Inside the main viewController:
#IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:
extension Array where Element == UIButton
{
func sharedButtonProperties()
{
for button in ButtonCollection
{
self.setTitleColor(.red, for: .normal)
//MARK: More properties will go here, once I get this to work.
}
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonCollection.sharedButtonProperties()
Now here is an example of an extension of a single IBOutlet of a UIButton that is working just fine, but not with a Collection:
//Inside the main viewController:
#IBOutlet weak var ButtonSingle: UIButton?
//Inside the extention file:
extension UIButton
{
func buttonProperties()
{
self.setTitleColor(.red, for: .normal)
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonSingle?.buttonProperties()
I am not an expert coder for sure, any help provided is greatly appreciated.
Thank you.
I have finally found the solution after so much trial and error. I want to share the answer with anybody that needs to set properties to UIButtons within an IBOutletCollection. This is a very efficient way to cut down time when you want to set/define properties to a group of buttons, or to all buttons project-wide.
I really hope someone finds this useful!
Code (Tested & Works): Note that what is in bold is what changed from the code I had in question.
//Inside the main viewController
#IBOutlet var ButtonCollection: [UIButton]!
//Inside the extention file:
extension Array where Element == UIButton
{
func sharedButtonProperties()
{
for **buttonGrp** in **self**
{
**buttonGrp**.setTitleColor(.red, for: .normal)
//MARK: More properties will go here now!
}
}
}
//calling the code inside main viewController, within "viewDidAppear"
ButtonCollection.sharedButtonProperties()
As you can see: I almost had it figured out, but all that was needed was to call the “buttonGrp” for the “for-in-loop", and to set this in “self”. I hope that makes sence!
Bye bye!

XCode doesn't load a custom view

I have created a custom view for an error message.
I created an ErrorView.swift sub classing UIView and I created also an ErrorView.xib to use in Interface Builder.
In the identity inspector I set the custom class of the xib as ErrorView.swift but
when I try to load this specific view it doesn't work.
Why? Can you help me?
This is the code:
My personalized class named ErrorView
Class ErrorView: UIView {
class func errorInView(view:UIView, animted:Bool) -> ErrorView {
println("ERROR VIEW LOADED")
let errorView = ErrorView(frame: view.bounds)
errorView.opaque = false
view.addSubview(errorView)
return errorView
}
}
my xib:
http://i59.tinypic.com/23tnlev.png
This is the code I use in my ViewController to call the view.
let errorView = ErrorView.errorInView(self.view, animted: true)
The problem here is that you are not loading your xib, instead you are creating a new Error View in code.
If you add errorView.backgroundColor = UIColor.greenColor() after errorView is created, but before you add it as a subview you will see the screen turn green. I have posted this example as a gist.
If you want to create your view from the xib you will have to load the xib using the normal NSBundle.mainBundle() call.
let errorView = NSBundle.mainBundle().loadNibNamed("ErrorView", owner: self, options: nil)[0] as ErrorView
instead of creating the view with the ErrorView(frame:)
This example is also a gist.

Window Sizing issue

I am creating a minimal WebKit browser for a Mac OS App using the following Swift code to load the new WKWebView into an Custom View Object.
The following line of code creates the web view to fill the size of the customView window:
var theWebView:WKWebView = WKWebView(frame:self.customView.frame)
When you run the App the web page loads correctly to fill the window, however if the window is resized the web page does not resize with the window.
I have added constraints to the Custom View object in interface builder and believe that this object is resizing correctly however it seems that the WKWebView is not adjusting to fill the Custom View?
See attached screen shots below.
Any ideas welcome.
import Cocoa import WebKit
#NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate
{
#IBOutlet weak var window: NSWindow!
#IBOutlet weak var customView: NSView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
//create a URL for the path
var url = NSURL(string:"http://www.google.com/")
//create a request for the URL
var request = NSURLRequest(URL:url!)
//create the WKWebView and set the size to match
//the window's full view
var theWebView:WKWebView = WKWebView(frame:self.customView.frame)
//have the web view load the page
theWebView.loadRequest(request)
//add the web view to the main window
self.customView.addSubview(theWebView)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
} }
I had this same issue (in Objective-C) and solved it by putting this one line of code in right after I added webView as a subview.
webView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;

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.

Required NSSlider method (sliderDidMove) declaration not found on Apple's Developer Documentation

Working on a tutorial with a NSSlider.
What I want: Moving the slider will show slider value in NSTextField.
Tutorial explains that following method will show slider value in text field:
- (IBAction)sliderDidMove:(id)sender {
NSSlider *slider = sender;
double value = [slider doubleValue];
[sliderValueLabel setDoubleValue:value];
}
Method does not work so I tried to find the method declaration on Apples developer website
but couldn't find it. From my understanding is the method: sliderDidMove a class method
from the class NSSlider so why I'm unable to find any documentation?
When slider value changes, it sends -[NSControl action] to its -[NSControl target]. So in Interface Builder you need to Ctrl-drag from the slider to the object that has sliderDidMove: (that will probably be either App Delegate or File's Owner). The name is chosen by the tutorial's author, it can be anything else.
Alternatively, you can set it up programmatically:
[slider setTarget:self]; // assume the handler is [self sliderDidMove:]
[slider setAction:#selector(sliderDidMove:)];
Note also that this particular task is better solved with bindings: bind both slider's and label's value to a double property of some object, and Cocoa will keep them synchronized.
In Swift ...
// Somewhere maybe in viewDidLoad ...
slider.target = self
slider.action = #selector(sliderDidMove)
// Later on..
func sliderDidMove(){
print("The slider moved!")
}