Change UIView (inside nib) background from other viewcontroller - iphone

Anyone know how to alter a view inside a nib from another viewcontroller? I have a outlet from the view in nib-file to the view class-file and I have #synthesize the view-class .m file. And then I #import "InfoView.h" (which is the view class) the view to the viewcontroller and at last I:
InfoView *infoView;
if (infoView == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"infoView" owner:self options:nil];
infoView = [nib objectAtIndex:0];
}
infoView.contentView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];"
But I can't get the background to change.
Has anyone tried to do something like this before?
I appreciate any input thank you!
EDIT:
Have addressed the UIColor issue but that was not the problem.

Try this code I have made the demo app for you.
create file CustomView.h
#import <UIKit/UIKit.h>
#interface CustomView : UIView
#property (nonatomic, strong) IBOutlet UILabel *titleLbl;
#end
CustomView.m. If you are using XIB
#import "CustomView.h"
#implementation CustomView
#synthesize titleLbl = _titleLbl;
- (id)initWithCoder:(NSCoder *)aDecoder
{
if(self = [super initWithCoder:aDecoder])
{
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomView" owner:self options:nil];
UIView *theEditView = [nibObjects objectAtIndex:0];
theEditView.frame = self.bounds;
[self addSubview: theEditView];
theEditView = nil;
}
return self;
}
Set fileOwner of CustomView.XIB is CustomView. and connect outlets.
Where ever you want to use CustomView take a UIView object in your XIB, and rename UIView class with CustomView. Create an IBOutlet in your .h file and connect it with CustomView object in XIB.
Now do this:
self.customViewObj.backgroundColor = [UIColor redColor];
self.customViewObj.titleLbl.text = #"Prateek";
In your case your customview object is not created. if you print your object it will show you nil.

You're using the -colorWithRed:green:blue:alpha wrongly. They expect a float value between 0 and 1. You need to do:
infoView.contentView.backgroundColor = [UIColor colorWithRed:50.0/255.0 green:50.0/255.0 blue:50.0/255.0 alpha:1];"

If you are trying to change the background color.. then do this:
infoView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:1];

Related

Terminating app due to uncaught exception 'NSInvalidArgumentException'

I am not getting an error now but my delegate is not working. I am making a custom keyboard so i have the UIViewController and a UIView. I want the UIView to call the sendKeyboardShortCut method in the UIViewController. The sendKeyboardShortCut method is not being called. Thank You
//ViewController .h
#import "KeyboardExtension.h"
#interface PageViewController : UIViewController <UITextViewDelegate,sendKeyboardShortCutDelegate> {
KeyboardExtension *inputAccView;
}
-(void)sendKeyboardShortCut:(NSString*)shortCut;
#property (nonatomic, assign) IBOutlet UITextView *tv;
#end
//ViewController .m
#implementation PageViewController
#synthesize tv;
- (void)viewWillAppear:(BOOL)animated
{
tv.delegate = self;
}
-(void)createInputAccessoryView{
inputAccView = [[[KeyboardExtension alloc] init]autorelease];
inputAccView.delegate = self;
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"KeyboardExtension" owner:self options:nil];
inputAccView = [nibObjects objectAtIndex:0];
}
-(void)textViewDidBeginEditing:(UITextView *)textView{
[self createInputAccessoryView];
[textView setInputAccessoryView:inputAccView];
}
-(void)sendKeyboardShortCut:(NSString*)shortCut{
if ([shortCut isEqualToString:#"dash"] ) {
NSRange range = tv.selectedRange;
if((range.location+range.length)<=tv.text.length)
{
NSString * before = [tv.text substringToIndex:range.location];
NSString * after = [tv.text substringFromIndex:range.location+range.length];
tv.text = [NSString stringWithFormat:#"%#-%#",before,after];
}
}
}
#end
//keyboard view .h
#import <UIKit/UIKit.h>
#protocol sendKeyboardShortCutDelegate <NSObject>
-(void)sendKeyboardShortCut:(NSString*)shortCut;
#end
#interface KeyboardExtension : UIView
-(IBAction)dash:(id)sender;
#property(nonatomic,assign) id<sendKeyboardShortCutDelegate>delegate;
#end
//keyboard view .m
#import "KeyboardExtension.h"
#implementation KeyboardExtension
#synthesize delegate;
-(IBAction)dash:(id)sender{[delegate sendKeyboardShortCut:#"dash"];}
#end
I suspect that:
1) your button's target is the nib's file owner and not KeyboardExtension
2) your action is setup not to send the sender, so UIKit calls -comma instead of -comma:
Also, the following code is highly suspect:
inputAccView = [[[KeyboardExtension alloc] init]autorelease];
inputAccView.delegate = self;
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"KeyboardExtension" owner:self options:nil];
inputAccView = [nibObjects objectAtIndex:0];
A) you allocate an object that you barely use as you replace it immediately with the nib's object
B) the way to extract the object from the nib ([nibObjects objectAtIndex:0]) is really not robust. You should create an IBOutlet in PageViewController and link it in the nib
I think you should revisit the way you use nibs here.
A final (unrelated) point: why are you using [NSString stringWithFormat:#"..."] instead of just #"..."?

Best Practice: Presenting a Subclassed UIView (with own xib) as subview of UIViewControllers

My goal is, to have a subclassed UIView (lets call it infoView) designed in his own XIB so that I can present it in many UIViewController's.
The Problem:
So far, when I was adding UIView's to a UIViewController I always had to make an UIViewController the file's owner of the UIView's .xib file to load the view with something like:
...
//this is inside the calling UIViewController's method
// InfoView *infoView is ivar and a subclass of UIView
infoView = nil;
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:#"InfoView"
owner:self options:nil];
for (id object in bundle) {
if ([object isKindOfClass:[InfoView class]])
infoView = (InfoView *)object;
}
[[self view] addSubview:infoView];
...
But I want to use the same UIView in many different UIViewController's, so I actually don't want a file's owner except maybe the class itself. In ThomasM's question he was setting the UIView itself to be the file's owner but without success.
In the answers there I found a solution to set the file's owner to nil. To do so I had to add all calling UIViewController objects from the Interface Builder object library to the InfoView.xib file and connect them with their infoView outlets.
But this doesn't feel right. So here I would like to collect solutions to
encapsulate a UIView together with his xib-file to use it in many different view controllers. How do you guys handle that?
Thx for any help.
EDIT:
The infoView is something like an overlay which appears when the user presses a button on one of the view controllers. It's NOT the View controllers "main" view. It gives detailed informations about the view of his superviews view controller and will disappear afterwards. I only fill the infoView with different contents threw out all the calling view controllers.
Like Hollance answer was pointing out I am using UINib.
To use it, leave the .xib files owner nil and place all customization of the infoView inside the initWithCoder: method of your InfoView class implementation. This will get called if you obtain the InfoView.xib like:
// here InfoView is the name of the .xib file
UINib *infoNib = [UINib nibWithNibName:#"InfoView" bundle:nil];
NSArray *topLevelObjects = [infoNib instantiateWithOwner:self options:nil];
QInfoView *infoView = [topLevelObjects objectAtIndex:0];
So you want to load a UIView from a nib that you wish to use in more than one UIViewController, and you want to connect it to an outlet on each of those view controllers. Is that correct?
Then make a UIViewController subclass (let's call it FakeViewController) with an IBOutlet property. Set that FakeViewController as the nib's File's Owner and connect your UIView to its outlet.
Done.
You just need to make sure all your other view controllers also have these outlet properties (although they don't need to be IBOutlets), but the nib loader doesn't actually check to make sure the class that you pass into the owner parameter equals the class name you specified in Interface Builder. So you can fake it.
Oh, and if you're OS 4.0 and higher, use UINib to load the nib file.
And yet another way is to create your own "controller" based on NSObject to define your own life-circle (instead of standard UIViewController life-circle).
For example:
BaseSubview.h:
#interface BaseSubview : NSObject {
UIView* _view;
}
#property (nonatomic, retain) IBOutlet UIView* view;
- (void)myMethod;
#end
BaseSubview.m:
#import "BaseSubview.h"
#implementation BaseSubview
#synthesize view = _view;
- (id)init
{
self = [super init];
if (self) {
// ...
}
return self;
}
- (void)dealloc
{
[_view removeFromSuperView];
[super dealloc];
}
- (void)myMethod
{
// view specific logic here
_view.backgroundColor = [UIColor redColor];
}
#end
InfoView.h:
#import "BaseSubview"
#interface InfoView : BaseSubview {
UILabel* _labelInfo;
}
#property (nonatomic, retain) IBOutlet UILabel* labelInfo;
#end
InfoView.m:
#import "InfoView.h"
#implementation InfoView
#synthesize labelInfo = _labelInfo;
- (id)init
{
self = [super init];
if (self) {
// ...
}
return self;
}
- (void)myMethod
{
// view specific logic here
_labelInfo.text = #"current time...";
[super myMethod];
}
#end
InfoView.xib:
file owner is InfoView
assign of outlets as usual
view is parent all other controls (such as labels, etc)
HugeAndComplicatedViewController.h:
// ...
// among other var definitions
InfoView* _infoView;
// ...
HugeAndComplicatedViewController.m, most interesting part:
// when you decide to show your view
// probably in loadView
_infoView = [[InfoView alloc] init];
[[NSBundle mainBundle] loadNibNamed:#"InfoView" owner:_infoView options:nil];
[self.view addSubview:_infoView.view];
// possibly perform specific logic
[_infoView myMethod];
// no need sub-view any more
// probably in dealloc
[_infoView release];
So now you have your own sub-view with logic and design separated from "Huge & Complicated" view-controller. It can have any life-circle you need for your current project.
does infoView need to be a subview?
in your viewController:
-(id) init {
self = [super initWithNibName:#"myNib" bundle:nil];
if (self) {
// code here
}
}

question about init and load from xib for a custom UIView

I am trying to create a custom UIView class which loads from a xim file that contains the interface for that view. I am trying to encapsulate the [NSBundle mainBundle] loadNibNamed...] within the init method of my custom view as follows:
- (id)init
{
self = [super init];
if (self)
{
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:#"LoadingV" owner:self options:nil];
self = [(LoadingV*)[nibViews objectAtIndex: 0] retain];
}
return self;
}
I want to know:
Is this an acceptable way of doing so? And is there any better way?
Should i keep the "retain" given that i do not call [self release] in dealloc?
Cheers
AF
No, this is not acceptable, it's bad practice and you actually have a memory leak there.
Better way to do this is to use a pattern called "factory".
Example:
#interface CustomView: UIView
#end
#implementation CustomView
- (void)awakeFromNib {
// custom view loaded from nib
}
#end
#interface UIView (Nib)
+ (UIView *)viewFromNib:(NSString *)nibName bundle:(NSBundle *)bundle;
#end
#implementation UIView (Nib)
+ (UIView *)viewFromNib:(NSString *)nibName bundle:(NSBundle *)bundle {
if (!nibName || [nibName length] == 0) {
return nil;
}
UIView *view = nil;
if (!bundle) {
bundle = [NSBundle mainBundle];
}
// I assume, that there is only one root view in interface file
NSArray *loadedObjects = [bundle loadNibNamed:nibName owner:nil options:nil];
view = [loadedObjects lastObject];
return view;
}
#end
Usage:
// CustomView.xib contains one View object with its class set to "CustomView"
CustomView *myView = (CustomView *)[UIView viewFromNib:#"CustomView" bundle:nil];

UIView subclass with its own XIB [duplicate]

This question already has answers here:
UIView and initWithFrame and a NIB file. How can I get the NIB file loaded?
(5 answers)
Closed 7 years ago.
I created a custom UIView subclass, and would prefer to not layout the UI in code in the UIView subclass. I'd like to use a xib for that. So what I did is the following.
I created a class "ShareView" which subclasses UIView. I created a XIB file with its file's owner set to "ShareView". Then I link some outlets I declared in my "ShareView.h".
Next I have a ViewController, MainViewController, which adds the ShareView as a subview. whith this code:
NSArray *arr = [[NSBundle mainBundle] loadNibNamed:#"ShareView" owner:nil options:nil];
UIView *fv = [[arr objectAtIndex:0] retain];
fv.frame = CGRectMake(0, 0, 320, 407);
[self.view addSubview:fv];
But now I get NSUnknownKeyException errors on the outlets I declared in my ShareView.
The reason I did all this is because I want a UIView, with its own logic in a seperate XIB file. I read in several places that ViewControllers are only used to manage a full screen, i.e. not parts of a screen...
So what am I doing wrong? I want my logic for ShareView in a seperate class, so my MainController class doesn't get bloated with logic from ShareView (which I think is an aption to solve this problem?)
ThomasM,
We had similar ideas about encapsulating behavior inside a custom view (say, a slider with companion labels for min/max/current values, with value-changed events also handled by the control internally).
In our current best-practice, we would design the ShareView in Interface Builder (ShareView.xib), as described by Eimantas in his answer. We then embed the ShareView to the view hierarchy in MainViewController.xib.
I wrote up how we embed custom-view Nibs inside other Nibs in our iOS developer blog. The crux is overriding -awakeAfterUsingCoder: in your custom view, replacing the object loaded from MainViewController.xib with the one loaded from the "embedded" Nib (ShareView.xib).
Something along these lines:
// ShareView.m
- (id) awakeAfterUsingCoder:(NSCoder*)aDecoder {
BOOL theThingThatGotLoadedWasJustAPlaceholder = ([[self subviews] count] == 0);
if (theThingThatGotLoadedWasJustAPlaceholder) {
// load the embedded view from its Nib
ShareView* theRealThing = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([ShareView class]) owner:nil options:nil] objectAtIndex:0];
// pass properties through
theRealThing.frame = self.frame;
theRealThing.autoresizingMask = self.autoresizingMask;
[self release];
self = [theRealThing retain];
}
return self;
}
You defined owner of the loaded xib as nil. Since file owner in xib itself has outlets connected and is defined as instance of ShareView you get the exception about unknown keys (nil doesn't have outleted properties you defined for ShareView).
You should define the loader of the xib as owner (i.e. view controller responsible for loading the xib). Then add separate UIView object to xib and define it as instance of ShareView. Then when loading the xib.
ShareView *shareView = [[[[NSBundle mainBundle] loadNibNamed:#"ShareView" owner:self options:nil] objectAtIndex:0] retain];
You can also define shareView as an IBOutlet in view controller's interface (and connect the outlet from file owner to that view in the xib itself). Then when you load the xib there won't be any need for reassigning the shareView instance variable since the xib loading process will reconnect the view to the instance variable directly.
I would like to add to the answer. I hope people would improve this answer though.
First of all it DOES work.
XIB:
Result:
I would like to subclass UIView for a long time especially for tableViewCell.
This is how I did it.
It's succesful, but some part is still "awkward" in my opinion.
First I created a usual .h, .m, and xib file. Notice that Apple do not have the check box to automatically create an xib if the subclass you created is not a subclass of UIViewController. Well create those anyway.
#import <UIKit/UIKit.h>
#import "Business.h"
#interface BGUIBusinessCellForDisplay : UITableViewCell
+ (NSString *) reuseIdentifier;
- (BGUIBusinessCellForDisplay *) initWithBiz: (Business *) biz;
#end
Really simple UITableViewCell, that I want to initialize latter with biz.
I put reuseidentifier which you should do for UITableViewCell
//#import "Business.h"
#interface BGUIBusinessCellForDisplay ()
#property (weak, nonatomic) IBOutlet UILabel *Title;
#property (weak, nonatomic) IBOutlet UIImageView *Image;
#property (weak, nonatomic) IBOutlet UILabel *Address;
#property (weak, nonatomic) IBOutlet UILabel *DistanceLabel;
#property (weak, nonatomic) IBOutlet UILabel *PinNumber;
#property (strong, nonatomic) IBOutlet BGUIBusinessCellForDisplay *view;
#property (weak, nonatomic) IBOutlet UIImageView *ArrowDirection;
#property (weak, nonatomic) Business * biz;
#end
#implementation BGUIBusinessCellForDisplay
- (NSString *) reuseIdentifier {
return [[self class] reuseIdentifier];
};
+ (NSString *) reuseIdentifier {
return NSStringFromClass([self class]);
};
Then I eliminated most init codes and put this instead:
- (BGUIBusinessCellForDisplay *) initWithBiz: (Business *) biz
{
if (self.biz == nil) //First time set up
{
self = [super init]; //If use dequeueReusableCellWithIdentifier then I shouldn't change the address self points to right
NSString * className = NSStringFromClass([self class]);
//PO (className);
[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
[self addSubview:self.view]; //What is this for? self.view is of type BGCRBusinessForDisplay2. That view should be self, not one of it's subview Things don't work without it though
}
if (biz==nil)
{
return self;
}
self.biz = biz;
self.Title.text = biz.Title; //Let's set this one thing first
self.Address.text=biz.ShortenedAddress;
//if([self.distance isNotEmpty]){
self.DistanceLabel.text=[NSString stringWithFormat:#"%dm",[biz.Distance intValue]];
self.PinNumber.text =biz.StringPinLineAndNumber;
Notice that it's really awkward.
First of all the init can be used in 2 ways.
It can be used to right after aloc
It can be used by we having another existing class and then we just want to init that existing cell to another biz.
So I did:
if (self.biz == nil) //First time set up
{
self = [super init]; //If use dequeueReusableCellWithIdentifier then I shouldn't change the address self points to right
NSString * className = NSStringFromClass([self class]);
//PO (className);
[[NSBundle mainBundle] loadNibNamed:className owner:self options:nil];
[self addSubview:self.view]; //What is this for? self.view is of type BGCRBusinessForDisplay2. That view should be self, not one of it's subview Things don't work without it though
}
Another icky things that I did is when I do [self addSubview:self.view];
The thing is I want self to be the view. Not self.view. Somehow it works nevertheless. So yea, please help me improve, but that's essentially the way to implement your own subclass of UIView.
You can create your custom UIView designed in xib and even make Interface Builder to display it inside other xib files or storyboards in new Xcode 6 using IB_DESIGNABLE. In xib set file owner to your custom class but do not set UIView class to avoid recurrency loading problems. Just leave default UIView class and you will add this UIView as a subview of your custom class view. Connect all your outlets to file owner and in your custom class load your xib like in the code below. You can check my video tutorial here: https://www.youtube.com/watch?v=L97MdpaF3Xg
IB_DESIGNABLE
#interface CustomControl : UIView
#end
#implementation CustomControl
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder])
{
[self load];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
[self load];
}
return self;
}
- (void)load
{
UIView *view = [[[NSBundle bundleForClass:[self class]] loadNibNamed:#"CustomControl" owner:self options:nil] firstObject];
[self addSubview:view];
view.frame = self.bounds;
}
#end
If you are using autolayout then you might want to change: view.frame = self.bounds; to:
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[view]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];
To use Yang's pattern with Auto-Layout, you need to add the following somewhere in the -awakeWithCoder: method.
theRealThing.translatesAutoresizingMaskIntoConstraints = NO;
If you don't turn off -translatesAutoResizingMaskIntoConstraints it can cause your layout to be incorrect as well as causing a LOT of debugging nonsense in the console.
EDIT: Auto-layout can still be a pain. Certain constraints aren't respected, but other are (e.g. pinning to the bottom doesn't work but pinning to the top does). We're not exactly sure why, but you can work around this by manually passing constraints from the placeholder to theRealThing.
It's also worth noting that this pattern works just the same way with Storyboards as it does with regular .xibs (i.e. you can create a UI Element in a .xib and drop it into a StoryBoard View controller by following your steps.)
Instead of subclassing UIView why don't you subclass UIViewController. Check out the following link. In that made a "RedView" and "BlueView" UIViewControllers with their xibs and added them to the MultipleViewsController view by creating and instance of the former two classes and adding [self.view addSubview:red.view] and [self.view addSubview:blue.view] in the MultipleViewsController's viewDidLoad method
MultipleControllers in one view
Just add (id)sender to the button pressed function in RedView and BlueView in the code of the above link.

iPhone - SubClassing UIToolbar the right way?

I created a new Class named
CustomToolbar
Then i created an empty nib, added a
toolbar to it, and set the toolbar
class to "CustomToolbar".
What is the proper way of initializing CustomToolbar In code so that my class uses the nib file?
I already have written the code to do that but i know it's not the correct way and it has a leak.
#interface CustomToolbar : UIToolbar {
}
#property (nonatomic, retain) IBOutlet UIBarButtonItem *button;
#end
#implementation CustomToolbar
- (id)initWithDelegate
{
NSArray *objects = [[NSBundle mainBundle]
loadNibNamed:#"CustomToolbar"
owner:nil
options:nil];
if (self = (CustomToolbar*) [objects objectAtIndex:0])
{
//do some work here
}
return self;
}
#end
The NIB will call initWithCoder: on your custom class, like this:
- (id)initWithCoder:(NSDecoder*)aDecoder {
self = [super initWithCoder:aDecoder];
if( self ) {
// Do something
}
return self;
}
If you really want to load it the way you do now, you need to retain the object returned from loadNibNamed.