PaperThick
PaperThick

Reputation: 2799

Change UIView (inside nib) background from other viewcontroller

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.

Upvotes: 1

Views: 329

Answers (3)

Prateek Prem
Prateek Prem

Reputation: 1544

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.

Upvotes: 2

chuthan20
chuthan20

Reputation: 5409

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];

Upvotes: 0

Bruno Koga
Bruno Koga

Reputation: 3874

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];" 

Upvotes: 0

Related Questions