2012-01-23 126 views
1

當我在我的超級視圖中創建UIView時,我想向此視圖添加一個按鈕作爲退出按鈕。 所以當按下時,它會從我的超級視圖中刪除這個UIView,我該怎麼做? 當按鈕被按下如何以編程方式向UIView添加退出按鈕

- (IBAction)skillButtonPressed:(UIButton *)sender 
{ 
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(40, 130, 240, 232)]; 
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [cancelButton setFrame:CGRectMake(0, 0, 32, 32)]; 
    [cancelButton setTitle:@"x" forState:UIControlStateNormal]; 

    [myView addSubview:cancelButton]; 
    [self.view addSubview:myView]; 
} 
+0

在那第一個視圖控制器你可以呈現的是一個導航控制器,UItabbar ..等等? –

+0

它在第一個viewController中創建,就像屏幕上的彈出窗口,所以退出按鈕將關閉此窗口 – Shakesbeer

回答

4

在你的類,創建視圖在視圖中查看和按鈕編程創建,增加一個功能是這樣的:

//tag for subview - make it unique 
#define SUBVIEW_TAG 9999 

- (void) handleExit 
{ 
    UIView * subview = [self.view viewWithTag:SUBVIEW_TAG]; 
    [subview removeFromSuperview]; 
} 

和創建子視圖時做:

- (IBAction)skillButtonPressed:(UIButton *)sender 
{ 
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(40, 130, 240, 232)]; 
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [cancelButton addTarget:self action:@selector(handleExit) forControlEvents:UIControlEventTouchUpInside]; 
    [cancelButton setFrame:CGRectMake(0, 0, 32, 32)]; 
    [cancelButton setTitle:@"x" forState:UIControlStateNormal]; 

    [myView addSubview:cancelButton]; 
    [myView setTag:SUBVIEW_TAG]; 
    [self.view addSubview:myView]; 

    //don't forget to release if you are not using ARC! 
} 
+0

我需要爲該按鈕創建單獨的方法嗎?當我觸摸按鈕時使用選擇器調用該方法? – Shakesbeer

+0

是 - 如果您使用的是InterfaceBuilder,那麼在視圖的頭文件中聲明一個** - (IBAction)handleExit; **函數,並將該按鈕的** Touch Up Inside **事件與該視圖連接起來。 –

+0

你介意告訴我如何以編程方式做到這一點嗎?因爲視圖和按鈕是以編程方式在我的情況下創建的 – Shakesbeer

1

這裏是你的代碼:

 self->myButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    self-> myButton = CGRectMake(60, 6, 180, 30); 
    [self-> myButton setTitle:@"MyButton" forState:UIControlStateNormal]; 
    [self-> myButton setTextColor:[UIColor whiteColor]]; 
    self-> myButton = 1; 
    [self-> myButton addTarget:self action:@selector(myButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside]; 
    [self addSubview:self-> myButton]; 

變化的座標爲您的按鈕放置

myButtonTouchUpInside方法implemetation,

[self removeFromSuperview]; 

希望這是你想要的..

+0

是的,那是我在尋找什麼,你介意告訴我如何實現myButtonTouchUpInside。我試過這樣的東西,但它不工作' - (IBAction)exitView:(UIView *)sender { [sender removeFromSuperview]; }' – Shakesbeer

+0

發件人是按鈕。你應該發送'removeFromSuperview'給自己,因爲三個不同的人已經告訴你。 –

+0

當我把[self removeFromSuperview];在該方法中,編譯器說:「實例消息的接收器類型'myClassName'沒有聲明一個選擇器'removeFromSuperview'的方法。」那有什麼問題? :( – Shakesbeer

1

你甚至可以隱藏視圖或[self removeFromSuperview];

相關問題