1

I want to create a different class with a view and call that class on screen. When I run the app, the view does not appear. If I delete that structure and create the button on the main file, it works fine. When I put it on a different class, it does not work.

MyView.h

#import <UIKit/UIKit.h>

@interface viewHome : UIViewController

-(UIView*) myHome;

@end

MyView.m (Creating a button for test)

#import "viewHome.h"

@implementation viewHome

-(UIView*) myHome {
    UIView * myScreen = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
    myScreen.backgroundColor = [UIColor whiteColor];

    UIButton * myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(100,100,100,44);
    [myButton setTitle:@"Login" forState:UIControlStateNormal];

    [myScreen addSubview:myButton];

    return myScreen;
}
@end

viewController.m [...]

- (void)viewDidLoad
{

    [super viewDidLoad];

    viewHome * fncScreen;
    UIView * homeScreen = [fncScreen myHome];
    [self.view addSubview:homeScreen];

}

Thanks

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201

3 Answers3

0

Its a bad practice to add one viewController's view as a subview to an another viewcontroller. (unless you are using certain classes/methods that let you have childViewControllers).

Its exactly for this reason, your view doesn't appear in one case, and appears in the other case.

try adding the -(UIView*) myHome method in your viewController.m, and do a

 [self.view addsubview: [self myHome]];

here's a good SO post about Nested UIViewControllers:

Is it wise to "nest" UIViewControllers inside other UIViewControllers like you would UIViews?

Community
  • 1
  • 1
Nitin Alabur
  • 5,812
  • 1
  • 34
  • 52
0

One obvious mistake I see in your code is this line:

viewHome * fncScreen;

OK, that's a pointer declaration, but you didn't actually create the object. You need something like this:

viewHome * fncScreen = [[viewHome alloc] init];

Then you can call methods on such initialized object.

Ivan Kovacevic
  • 1,322
  • 12
  • 30
0

You could call the method [fncScreen myHome] after allocation your view homeScreen. like this -

UIView *homeScreen = [[UIView alloc] init];
homeScreen = [funScreen myHome];
[self.view addSubView: homeScreen];
[homeScreen release];

Hope this will help you.

  • That's the same I wrote :) btw, he probably will not need the last line of your code snippet, in fact it will even throw an error. ARC is the default option for the last 2 years! – Ivan Kovacevic Feb 26 '13 at 15:20