UIButton以编程方式创建但未显示在视图上(addSubview被调用)

时间:2012-08-07 17:10:48

标签: iphone objective-c ios uibutton

拥有AppDelegateMainViewController。 在MainViewController UIButton创建了AppDelegateMainViewController设置了背景图片,并应在UIButton上显示。这几乎就是它,但我看不到IBOutlet

为了对齐目的,我创建了一个@property (strong, nonatomic) IBOutlet UIButton *searchBtn; 并连接了IB中的按钮。

MainViewController.h

@synthesize searchBtn;

MainViewController.m

@synthesize mainVC;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ViewController > setup:
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.mainVC = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    self.window.rootViewController = self.mainVC;
    self.window.backgroundColor = [UIColor whiteColor];

    // Buttons > Set background images:
    [self.mainVC.searchBtn setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];

    [self.mainVC.view addSubview:self.mainVC.searchBtn];

    [self.window makeKeyAndVisible];

    return YES;
}

AppDelegate.m

{{1}}

2 个答案:

答案 0 :(得分:6)

如果您是以编程方式创建它,首先不需要IBOutlet

其次,您可能希望在视图控制器的viewDidLoad而不是AppDelegate中移动按钮的创建。这是你的视图控制器的业务。

如果您以编程方式创建按钮,则可能应该alloc init按钮:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(...)];
[button setBackgroundImage:someImage];
[button addTarget:self action:@selector(something:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];

类似的东西。

答案 1 :(得分:1)

您应该在MainViewController类中添加按钮,而不是首先关闭AppDelegate。

您还应该在MainViewController中设置视图的背景,而不是AppDelegate。

它应该是这样的:

AppDelegate.m

@synthesize mainVC;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ViewController > setup:
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.mainVC = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];
    self.window.rootViewController = self.mainVC;

    [self.window makeKeyAndVisible];

    return YES;
}

在你的MainViewController.m中,viewDidLoad把这个

- (void)viewDidLoad {
    [super viewDidLoad];
    // Buttons > Set background images:
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];

    //If you adding the button in Interface Builder you don't need to add it again
    //[self.view addSubview:self.mainVC.searchBtn];
}