Objective-C can someone explain how to programmatically display a view - objective-c

I'm just not getting this, I want to display a view in my app when a user clicks a button.
I've gotten this far:
NSView* unitMarker = [[NSView alloc] initWithFrame: NSMakeRect( 20.0, 20.0, 80.0, 50.0 ) ];
How would I display this view with a red background?
Thanks

#Aaron: he says he wants to do this programmatically. Also he's using NSView, not UIView, so an iPhone tutorial would be almost irrelevant.
#Mike: Your description of what you want to do is a bit vague. We have a bit of code creating, a view, but no context to tell us exactly what you are trying to do. Do you want the view to come up in a new window or the same? Do you want to replace a view that's already there? We don't even really know your skill level.
I suggest you go check out the documentation for NSView: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html

I've gotten this far:
NSView* unitMarker = [[NSView alloc] initWithFrame: NSMakeRect( 20.0, 20.0, 80.0, 50.0 ) ];
How would I display this view with a red background?
You wouldn't, because a plain NSView doesn't draw anything.
First, you need to subclass NSView, implement drawRect: in that subclass to fill its bounds with red, and instantiate that subclass instead of NSView directly.
You should read the View Programming Guide.
How would I display this view …
You wouldn't. The view displays itself when it is appropriate to do so.
It won't ever be appropriate for it to draw itself until you add it to a view hierarchy. Every window has one, rooted at its content view. You need to add this view either to a content view or to some descendant view (subview, subview of a subview, etc.) of a content view.
You normally should not tell a view to display from your controller. That's the window's job. When you do change a property or properties of the view that affect what it draws, set the view as needing display, and let the window tell the view to display when it's appropriate to do that.

Say this out loud 10 times repeatedly:
Interface Builder is my friend.
I was able to put together a sample project doing exactly what you want to do in about 5 minutes by leveraging Interface Builder as part of the process. http://www.markdouma.com/developer/ShowWindowWithRedView.zip.
You can't show a view without placing it in a window first; by far the easiest way to do this kind of a thing is to drag out a second window in Interface Builder, set it to not be visible on launch, drag a generic NSView custom view onto the Window, set its class to be SRRedView (your red view subclass). As d11wtq posted, you override NSView's primitive drawing method like he shows (though personally I prefer NSBezierPath :-P).
In your controller class, you define IBOutlets, and then hook those up in Interface Builder. These provide you with a way to reference the important parts of your interface so that you can manipulate them programmatically.
I added one IBAction method, which the button in the main window is hooked up to call. That method simply tells the second window to show itself.
- (IBAction)showWindowWithRedView:(id)sender {
[windowWithRedView makeKeyAndOrderFront:nil];
}
In the 8 years or more that I've been doing Cocoa programming, I don't think I've ever needed to resort to manually creating windows and views. It has always been much faster to simply load another nib file that contains the windows or views I need to display. Using Interface Builder along with Xcode to create your app is quite a bit different than how other IDEs work. (Specifically, when you arrange stuff in Interface Builder you're not generating code as much as you are creating instances of UI objects and then "freeze-drying" them in their current arrangement into a .nib archive file. When you launch the app, they are brought back to life. Or at least that's the way I think about it).

You need to subclass NSView and implement drawRect:.
In this case you're just going to fill the entire rect with red.
#interface MyView : NSView {
}
#end
#implementation MyView
-(void)drawRect:(NSRect)dirtyRect {
[[NSColor redColor] set];
NSRectFill(dirtyRect);
}
#end
That's an extremely basic example that does what you want, but if you want to do more complex things (adding borders (strokes) or drawing curves (paths) etc), then you need to learn all the drawing classes available to you.
Scott Stevenson has written some easy to follow tutorials on this:
http://cocoadevcentral.com/d/intro_to_quartz/ and;
http://cocoadevcentral.com/d/intro_to_quartz_two/

Related

How to show a uiview alway on top?

I want to show a logo UIView always on top when the app running,
I know there is a way to do that,add same UIView to every UIViewController,
but I think this is not the best way to do that.
when i have lot of pages,and modify the logo UIView,must modify it every page.
Did someone have better way to do this?
thanks.
look like this:
Since you only every have one window per app, and view's don't have levels, you have to make sure that view stays on top of the hierarchy, no matter what. One relatively easy way is to add it directly to the window above the rest of the interface (the navigation controller):
In applicationDidLaunch:
// After the main navigation controller or tab controller has been added
// either programmatically or in the xib:
UIImage *logo = [UIImage imageNamed:#"logo.png"];
UIImageView *logoView = [[UIImageView alloc] initWithImage:logo];
[self.window addSubview:logoView];
Actually, I think that (a) creating a subclass of UIView that shows your logo and has all the necessary setup in it and then (b) adding this subclass to each view controller is the cleanest and most manageable way to do this.
The reason I prefer this method over adding the view to the window is because if you ever have a view that you don't want to show the logo, you won't need to show and hide something you added to the window. Also, adding directly to the window may cause rotation challenges on certain iOS devices in my experience, depending on what you're doing.
Also, to make sure your logo view is always on top of the view hierarchy, you can do two things:
If the view already exists, you can bring it to front using [UIView bringSubviewToFront:]
[myParentView bringSubviewToFront:myLogoSubview];
If you are creating the view, it will be on top when you add it with [UIView addSubview:]
// Set up myLogoSubview first here with alloc+init, etc.
[myParentView addSubview:myLogoSubview];`
It looks like in your image you would replace myParentView with self.view and myLogoSubview with the view you're looking to keep on top, but this is just my assumption based on your image.

Accessing class that added scrollview as a sub view and some other questions

I'm working on an iOS app. Basically, one section of my app has a large scrollview with 6 other scrollviews added as sub views (using the method [scrollView addSubview:object.view]) so that it pages between 6 different scrollviews. Each scrollview has some textviews that I need to save the contents of.
In each sub scrollview, I added an inputAccessoryView to the keyboard to add a Done button, and I want to call a method to save the data when this button is pressed, and then remove the keyboard (the latter of which I already have done, I just need to figure out the saving part).
I feel that it would be easier to have one method in my 'super' scrollview that will save all of the data so I can just add in a few lines of code to each sub scrollview (by the way, these sub scrollviews aren't subclassed from the main scrollview, they are UIViewController subclasses, so I can't just use super) because I have to copy/paste it into 6 different files. I was able to access the 'super' class (the big scrollview that has all of the others in it) by importing it in the 'sub' scrollview and creating a new object, but I feel that's not what I'm supposed to do. That leads me into my next question.
If access the bigger scrollview in this way, trying to access the text property of the UITextViews returns null, whereas accessing the same property from within the class of the sub scrollview displays the text.
Please let me know if I'm doing something completely wrong, as I feel like having 6 different scrollviews is really inefficient (but testing it on two iPod touches, a 2nd gen and a 4th gen, there isn't much lag at all so it can't be too inefficient or else it'd hog memory and make it lag, right?)
Thanks,
Lee
EDIT:
I'm still having trouble with this. The button I created was created programmatically, so I can't link it to the first responder in Interface Builder. Is there a way to do this programmatically as well? Here's my code to create the inputAccessoryView:
-(void)createInputAccessoryView{
inputAccView = [[UIView alloc]initWithFrame:CGRectMake(10.0, 0.0, [[UIScreen mainScreen] bounds].size.width, 40.0)];
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 40.0)];
UIBarButtonItem *doneBttn = [[UIBarButtonItem alloc]initWithTitle:#"Done" style:UIBarButtonItemStyleDone target:self action:#selector(endEdit:)];
[toolbar setItems:[NSArray arrayWithObject:doneBttn]];
[inputAccView addSubview:toolbar];
[toolbar release];
[doneBttn release];
}
The button points to a method (in the same class) that will close the keyboard. However, before I close the keyboard, I need it to call another method to save the data (which is in a different class). Does this help anyone's understanding?
When posting a question, show your code. Don't just describe your code. It's much easier for us to help you when we can see what you're talking about without the filter of what you think is important.
Nevertheless, I think I know what you are doing wrong and how to help you. You said this:
I was able to access the 'super' class (the big scrollview that has all of the others in it) by importing it in the 'sub' scrollview and creating a new object ... trying to access the text property of the UITextViews returns null
It sounds like you have put this in your child scrollview:
- (IBAction)saveButtonWasPressed:(id)sender {
ParentScrollView *parent = [[ParentScrollView alloc] init];
[parent saveEverything];
}
and then you expected this newly-created parent scroll view to be hooked up to your existing text views. But why would it be connected? When you load a view hierarchy from a nib, the nib loader takes care of making the connections that you established using Interface Builder. But if you create views in code, you have to establish the connections yourself, and you didn't.
You shouldn't be creating a new parent scroll view anyway. You need to send a message to the existing parent scroll view. There are a few ways you could do that. In this case I recommend using the responder chain.
You can read about the responder chain in Cocoa Application Competencies for iOS. Here are the important concepts for this problem:
When a text view is active, the text view is the first responder in the chain.
Each ancestor view of that text view is in the chain.
You can hook up a button to send an event up the responder chain when the button is touched:
In Interface Builder, you just connect the button to the "First Responder" placeholder (in the upper-left area of the window). You need to have already defined the IBAction in your source code for it to show up when you connect the button to the First Responder placeholder.
In code, you use nil as the target parameter of addTarget:action:forControlEvents:, like this:
[self.saveButton addTarget:nil action:#selector(saveEverything:) forControlEvents: UIControlEventTouchUpInside];
If you hook your button up that way, UIKit will take care of searching the responder chain for the first responder that responds to the saveEverything: message. In your case, that should be your (existing) parent scroll view.
One more thing: the parent scroll view isn't really the right place to put your save code. In the MVC design pattern, a controller is more appropriate. Lucky for you, if a view has a UIViewController associated with it, the UIViewController is also in the responder chain. So you can put your saveEverything: method on your view controller instead of your parent scroll view.

Custom UISplitViewController?

I want the effect of a UISplitViewController however I am not using the split view template.
Is it relatively easy to achieve without the template? And with using normal UIViewController?
What I want it a customary sized and positioned UITableView which then has a customary sized detail view which then of course goes into a popover and detail view when portrait.
Doing it without Interface Builder, you would create a UIViewController class. In the viewDidLoad method of that class, create a UIView or a UITableView with the frame origin where you want it and a size that you want. (Release it in the viewDidUnload method.) Then set the UIViewController's self.view to point to this new view.
self.view = [[UIView alloc] initWithFrame:...]; // edit - added in response to your question
If you created a UIView, then you will want to put your UITableView inside this new view. (This approach lets you add more items to the container UIView if you need to.)
Make sure your UIViewController adheres to the UITableViewDelegate and UITableViewDataSource protocols. Add the delegate and datasource methods and you should be good to go.
This new view can cover other views, or you can size the other views to fit beside it. You only need to set there frames according to what you want to do with them.
There are some limitations if you use a UITableViewController, so a lot of people recommend using a UIViewController instead. like I described above. You can google for more info on that topic.
Just great a new temporary Xcode-project from that template and judge yourself, if it is complicated for you, to adept your (real) code.
Yes. You can do it quite easily. Just use delegates to pass messages between the left and the right side views (root and detail). For instance the didSelectRowAtIndexPath tableView method could be used along with delegation to pass a message to the right sided detail view. Tap a cell on the left table, show its text as a Label on the right side. Its just a simple example. And yes you can handle the rotations and send left side view into a UIPopoverController as well, thus giving the detail view full screen real estate in Portrait orientation.
Also try MGSplitViewController . It gives you a lot of other customization options on a split view controller.

Should I use IB or Subclass UIView

So, I developed a kind of drop down button class.
Let's call it DDButton.
I mainly export one function :
-(void) addButtonWithImage:(UIImage*)image andTarget:(id)target andSelector:(SEL)selector
which lets the user add another button to the drop down.
I will need to use DDButton in different screens of my app.
I would like to use it like:
DDButton* ddb = [[DDButton alloc] initWithFrame:rect];
[ddb addButtonWithImage....]
[ddb addButtonWithImage....]
My question is since I never subclassed UIView before how should I implement it, and how should I use it later ?
Do I use IB and create a stub UIView which I'll connect to the DDButton in the Identity Pane ?
if so , how exactly I instantiate the view later on.
Or,
Do I subclass UIView ? if so , what methods I should override ? Do you I setup my buttons in the initializer ? in LayoutSubView ? In drawRect ?
I would love to hear the best approach here.
Thanks!
Edit
Let's say I choose the IB way : I have a main button which I set regardless of the
addButtonWithImage() calls, actually all calls to addButtonWithImage just "append" to that button. I want to main button to be the size of the view, until other buttons are added and then the view grows appropriately. However, I want the size of the view to be chosen by the user at first...using setFrame I guess.
Meaning in the awakeFromNib I can't count on the frame size yet (it only take the xib size I assume). So where would I setup my main button ? LayoutSubView ? setFrame ? I'm not sure.
Add your view to the interface in IB as a UIView, then change the class in the identity pane. If you need to do initialization in code, use a -(void)awakeFromNib method. I would suggest setting up the buttons when they are added in addButtonWithImage....
I'd probably do a subclass, building views in code is a good thing to learn.
Override drawrect: to do any custom drawing you need to do, if you're just adding a UIImageview or something and doing positioning you could just override initWith...: and do your custom initialisations.

Looking for info on custom drawing of interface components (Cocoa)

It seems like more and more OS X apps these days are doing all kinds of fancy drawing stuff for custom controls. Apps like Twitterific, Things, EventBox, Versions just to name a few....
So basically I'm looking for any information on how to get started doing this kind of thing. Not sure if it is just done by subclassing controls and using custom drawing or if it is something entirely different.
Any help is greatly appreciated. THanks!
It depends entirely on what you want to do.
The "Show Raw Properties" button in Versions for instance is an NSButton subclass, because basically what we needed is standard button behavior with our own look.  One way to subclass a button is to simply implement your own -drawRect:(NSRect)rect method in the NSButton subclass, but we decided to stick with the way NSButton is implemented in Cocoa, meaning most drawing is done by the button's cell, so the implementation looks like this:
In the NSButton subclass:
+ (Class) cellClass
{
return [OurButtonCell class];
}
- (void)drawRect:(NSRect)rect
{
// first get the cell to draw inside our bounds
// then draw a focus ring if that's appropriate
}
In the NSButtonCell subclass (OurButtonCell):
- (void)drawInteriorWithFrame: (NSRect) rect inView: (NSView *) controlView
{
// a bunch of drawing code
}
The Timeline view in Versions is actually a WebView, the page that you see in it uses javascript to collapse headers you click on.
The rule of thumb I use for where to start out with a custom control is:
To customize the look of a standard Cocoa control:
subclass the appropriate control (like e.g. NSButton and NSButtonCell)
stick as close as makes sense to the way the default control is implemented (e.g. in a buttoncell, start from the existing attributedTitle instance method to draw the button title, unless you always want to draw with the same attributes regardless of what's set up in IB or if you need to draw with different attributes based on state, such as with the trial expiration button in Versions' main window)
Creating an entirely new UI element:
subclass NSView and implement pretty much all mouse and key event handling (within the view, no need to redo "hitTest:") and drawing code yourself.
To present something that's complex, of arbitrary height, but isn't a table:
See if you can do it in HTML, CSS and JS and present it in a WebView.  The web is great at laying out text, so if you can offload that responsibility to your WebView, that can be a huge savings in pain in the neck.
Recommended reading on learning how to draw stuff in your own custom view's drawing methods: Cocoa Drawing Guide
Customizing the look of for instance an NSTableView is an entirely other cup of tea, thanks to the complexity of a tableview, that can happen all over the place.  You'll be implementing your own custom cells for some things you want to do in a table, but will have to change the way rows are highlighted in a subclass of the actual NSTableView object itself.  See for instance the source code for iTableView on Matt Gemmell's site for a clear example of where to draw what.
Finally, I think Abizer's suggestion to go check out the code of BWToolkit is a great idea.  It might be a bit overwhelming at first, but if you can read and understand that code you'll have no trouble implementing your own custom views and controls.
Have a look at some excellent example code: BWToolkit