Is there a shortcut to accessing a xib's initial attributes? - ios

I do a lot of animations with UIKit and I frequently store any animated view's initial frames in viewDidLoad to always have a reference to the frame as it appears in a xib.
This is kind of smelly and seems like the kind of thing that would be automated, but I can't seem to find any info on this. Is there a property on UIView that stores initial xib frame sizes? Or maybe a UIKit utility method that scans the xml of a xib for it's attribute values by name?

So while I could not find any way to access an interface builder file's initial attributes (unless you count writing an IB XML parser a way), I found a brilliant alternative from Do I need to set heightForRowAtIndexPath if I am using a custom UITableViewCell?. Instead of accessing some constant values from an object itself (I was hoping for a self.attribute.nib.value), you can make two outlets per IB object- one for manipulating, and one for a prototype- which will hold all the original values of the xib.
To makes things simple, just create an(other) outlet for your nib and override its getter.
For example, if we have a LargeCell.xib, we would create an outlet for largeCell and another for largeCellPrototype.
Then we would make a lazy accessor for this prototype to ensure the prototype is not nil and only loaded once.
- (LargeCell*)largeCellPrototype
{
if (!_largeCellPrototype)
{
[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LargeCell class]) // Presuming you don't name files with reckless abandon
owner:self
options:nil];
}
}
now getting the initial values is as simple as
CGFloat initialViewHeight = self.largeCellPrototype.frame.size.height;

Related

Showing a content of a UIView loaded from a xib in a storyboard

Current Setup
I have a subclass of a UIView that loads a content from a xib file - call it a XibOwnerClass. Also, among other classes, there is a class called Triangle which helps me to create triangles with or without a border, with different stroke or fill color etc. That class is designable in storyboard and some of its properties are defined as IBInspectable.
Currently, in my xib file, I use this triangle view and setup its inspectable properties through IB. And that is really cool and convenient... So if I look into xib, I will actually see the triangle view among other views.
So, lets go further. In order to use this XibOwnerClass, I drag the UIView element to the storyboard, and change its custom class to XibOwnerClass, so I get my designable properties specific for XibOwnerClass. So, I can setup all things in IB and when I run the app, everything works.
The problem
Even if this works, I wonder if there is a way, to have multiple views (of class XibOwnerClass) dragged on a storyboard, and to be able to configure all of them individually trough Interface Builder?
Currently when I drag the UIView and change its custom class to XibOwnerClass I see nothing. I mean, the view is there, and it has its standard properties + inspectable properties. But I can't see triangles defined in xib in this new view. Is there a way to do this?
I am aware that xib is reused in my case (and it is meant to be used like that), so if I change something in a xib, all views that load from it will be affected. But is there a way multiple views to load from the same xib, but when loaded, to see them & setup them individually?
Here is how I load from xib:
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super initWithCoder:aDecoder])){
UIView *myView = [[[NSBundle mainBundle] loadNibNamed:#"MyXib" owner:self options:nil] firstObject];
if (myView){
myView.frame = CGRectMake(myView.frame.origin.x, myView.frame.origin.y, self.frame.size.width, self.frame.size.height);
[self addSubview:myView];
//Initialize other stuff
[self commonInit];
}
}
return self;
}
Then in awakeFromNib: I use the values of inspectable properties...
EDIT:
Also I don't have initWithFrame: implemented, but I thought that it is not needed if load from nib (because it is not executed). But maybe this is needed while design time ?
can't really say what's wrong when you don't share class codes. but i guess you didnt use prepareForInterfaceBuilder. in your XibOwnerClass override prepareForInterfaceBuilder and call setups for view inside it for example change background colour or so.
override func prepareForInterfaceBuilder() {
//prepare setups or things to show in storyboard
}
Okay, I have solved it. It turned out that I shouldn't use Main Bundle but rather bundle for that class, like described here.
So here is the code:
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
#Mohammadalijf's answer in general is correct. It is just not a direct solution for my issue. But later on, when I fixed bundle thing, I used prepareForInterfaceBuilder like he said, and initialized things there so everything was available at design time.
Some useful stuff related to all this can be found here as well.

How are NSTableCellViews supposed to be laid out?

I have a fairly basic MainWindow.xib with a source list-style sidebar. I created it by dragging the Source List template into the window, which already contains two NSTableCellViews: HeaderCell and DataCell.
The latter consists of an icon (using NSImageView) and a label (NSTextField). Instead, I want the label and another, smaller label underneath. In IB, this looks as follows:
If I focus on just DataCell, it highlights accordingly:
Thing is, actually running the program, it looks nothing like the template:
Notice how the two NSTextFields just get smashed together into one. My understanding was that view-based NSOutlineViews (and view-based NSTableViews, for that matter) are supposed to be designed as a template from within IB. Instead, the dimensions from the template seem to get mostly ignored.
Here's the code that sets the view's values from the data source:
public class TourSourceListDelegate : NSOutlineViewDelegate
{
public override bool IsGroupItem(NSOutlineView outlineView, MonoMac.Foundation.NSObject item)
{
return (item as TourSourceListDataSource.Item).IsHeader;
}
public override NSView GetView(NSOutlineView outlineView, NSTableColumn tableColumn, MonoMac.Foundation.NSObject item)
{
if (IsGroupItem(outlineView, item))
{
return outlineView.MakeView("HeaderCell", this);
}
else
{
var data = item as TourSourceListDataSource.Item;
var dataView = outlineView.MakeView("DataCell", this);
(dataView.Subviews[0] as NSTextField).StringValue = data.Name;
(dataView.Subviews[1] as NSTextField).StringValue = data.Date_start.ToShortDateString();
return dataView;
}
}
}
I've tried overriding GetRowHeight, but that doesn't seem to resolve the problem (it makes more room, but still doesn't let the views distribute themselves properly), nor does it seem necessary.
I've also tried playing with the various Autosizing, Autoresizes Subviews, etc. toggles in IB, but that doesn't seem to produce intuitive results, and again, it doesn't seem necessary — the view as presented in IB is exactly what I want, just with slightly longer labels in practice.
I haven't tried converting this to AutoLayout yet.
What obvious step am I missing?
Some more info that probably doesn't make a difference: this is a Xamarin.Mac/MonoMac project with Xcode 5.0, MacOSX10.8.sdk, Xamarin Studio 4.0.12, Xamarin.Mac 4.0.12, and Mono 3.2.3 (targeting Mono / .NET 4.0). I've also enabled App Sandboxing.
What's important in interface builder is the view hierarchy. What kind of view is that cell? Are those labels really subviews of the cellview or not? The hierarchy should look something like:
One thing that's fishy that I see is accessing dataView.Subviews[0] and [1]. If you're adding subviews to your cells then should be creating your own NSTableViewCell subclasses, with each view connecting to the subclass' IBOutlet properties. The subclass doesn't need any code in its implementation, just the declaration of its properties in #interface, such as titleField and descriptionField, and an empty #implementation that auto-synthesizes them.
Then makeViewWithIdentifier (or apprently the glue MakeView in Xamarin) when passed the right identifier should create your NSTableViewCell subclass, and at runtime you can verify that using po dataView in the debugger. Then you access the subviews using the properties of your NSTableViewCell subclass' interface instead of assuming which view is in which position with the subview array, using dataView.titleField and dataView.descriptionField.
If your cell view has one text field then you can use NSTableViewCell without subclassing, but do connect up the textField outlet (its connected by default as long as you don't delete & recreate the cell view's label view) so you can access it through the property, again instead of having to dive into the subviews array.
All that said, it's not really clear why you're seeing what you are. It looks like those aren't the subviews you expect, and might even look like the wrong fonts as well as in the wrong positions. Using a custom subclass of NSTableViewCell and verifying its class at runtime is a good way of making sure it's creating the view you expect, but you can also dump the subview within the debugger using po [dataView _subtreeDescription].

ios uiview subviews-loaded-event

Is there an easy way to know when all the subivews have loaded?
Right now I'm doing:
if([[self subviews] count] == 10) {
//do stuff
}
If there isn't an event/method for this, is there at least a way to dynamically know what the child count is GOING to be?
edit
I re-read this just now and realize it's a bit asinine. Let me clarify:
I'm loading this UIView from a XIB file and I wanted to know when the NIB has officially loaded (with all of it's children). So I dare say the correct answer would be awakeFromNib
If you're calling this from a viewController, just use
-(void)viewDidLoad;
Which is called after the view and all its subviews are loaded. If you're doing it from one of the views inside the nib, use:
-(void)awakeFromNib;
Which is called after the view's subviews have been loaded.
If you are adding subviews programmatically (e.g. [myView addSubview:anotherView]), then of course there is no way to know; the program could add more subviews at any time, if you write it that way.
If you are loading the view from a nib, you are probably looking for the awakeFromNib method. From the NSObject UIKit Additions Reference:
The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

Where to place the code to change the properties of a UIView

If I'm creating a UIView programmatically and I wish to change the UIView properties (background, for example, or actually, messing with CALayers), must I place the code outside of UIView such as in the View controller? Can I put the code somewhere inside UIView?
I was checking out the CoreAnimationKioskStyleMenu example, its code is inside UIView but it's loaded from Nib and can be placed at awakeFromNib, so it doesn't seem to apply to my case.
That depends. Obviously, a good way to handle this is to use a xib file, as it is designed to hold data like this, but that isn't always the best answer for every situation.
If the view is meant to be reused frequently (like a button, or some widget) throughout the application, its best to store all that customization in a subclass of the UIView.
If its a single larger view that will always be managed by a UIViewController, you can keep some of the information in the UIViewController. However, if you end up subclassing a UIView anyway it's probably best practice to keep the data in the UIView.
As a general note, I believe its worth your time to push as much of this data into a xib using interface builder. Magic values (like colors or sizes) peppered through your code will always be a problem if you want to modify it. I have found modifying a xib to be much easier.
Actually there are some methods where you could place initialization/ customization code.
(void)willMoveToSuperview:(UIView *)newSuperview;
(void)didMoveToSuperview;
will get called as soon as u add the view as a subview to another view, at which point you already have the frame and all the properties, and you can do further customizing as you wish.
(void)layoutSubviews -- generally used for changing subviews' frames and layout organization.
Will get called each time the view needs to be redrawn by the system, or when you specifically call [self setNeedsLayout] on your UIView.
Hope this helps.

Programmatically accessing subviews of UIView added in Interface Builder

I have a nib file where I have a view that contains a background image, a button and another image that covers the full screen (a shadow) that needs to be moved to the front.
On the view, I'm creating child views, and after creating those and adding them using [self addView] I need to move to the front the shadow image.
I'm currently using the tag attribute to find that view, but I'm thinking there's probably a better way, by means of identifying the subviews I add in Interface Builder by some name.
I tries adding a IBOutlet to connect the subview with its parent, but it didn't work (and made no sense, since the subview is already connected to its parent in some way).
The IBOutlets way should work, and is probably the best way to do it. Make sure you made the proper connection in Interface Builder after you declared them in the .h file.
The iPhone does a lazy loading of view controllers. The nib might not have been loaded in initWithCoder or any init method for that matter as Kendall specified.
viewDidLoad is the preferred place to access anything from the nib if you want to access them before the view is displayed.
Hope that helps.
At what point are you trying to access the subviews? If you try within init of a ViewController, the IBOutlets will be nil. The first method you can get at them is probably viewDidLoad.
The reason it does make sense to do things this way is that IBOutlets are just direct pointers to some component, even if they are already subviews of something else. Just saves a lot of hunting.
Using the Tag is a perfectly valid way to locate specific views, so long as you're using the viewWithTag: method. If you're already using tags, there's no need to change to IBOutlets unless you just don't like calling viewWithTag:.

Resources