[英]Click event of UIButton is not getting fired
我制作了一個簡單的應用,其中每個方向上都加載了不同的.xib
,
我有兩個廈門國際銀行的Portxib
和Landxib
,在這兩個xibs,我拖着一個按鈕和分配
在兩個xib中將其標記為1
。
我在viewDidLoad
編寫了這段代碼
UIButton *btn=(UIButton *)[self.view viewWithTag:1];
[btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
這是選擇器方法,
-(void)BtnClick:(id)sender
{
NSLog(@"BtnClick");
}
UIButton的點擊事件未觸發...
要么
還有沒有其他方法可以從兩個方向調用相同的按鈕方法?
編輯:
.h file
.m file
確保...
xib
,你在尋找它self.view
或者確保它被放置在正確的觀點,並使用這一觀點viewWithTag
編輯
我感覺您的視圖在設置代碼的viewDidLoad
上沒有得到認可。 因此,只需在viewDidLoad
注釋掉該代碼,然后在加載筆尖后移入changeOrientation方法即可。
-(void)changeOrientation
{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if(orientation==UIInterfaceOrientationPortrait || orientation==UIInterfaceOrientationPortraitUpsideDown)
{
[[NSBundle mainBundle] loadNibNamed:@"PortraitXib" owner:self options:nil];
}
else
{
[[NSBundle mainBundle] loadNibNamed:@"LandscapeXib" owner:self options:nil];
}
//Adding this code here makes sense that nib is loaded and after that we are recognizing button from loaded view of nib.
UIButton *btn = (UIButton*)[self.view viewWithTag:1];
[btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
希望這可以幫助。
在頭文件中添加
IBOutlet UIButton *btn;
從您的xib文件中引用此btn。
在這種情況下,xib文件未引用您正在使用的btn,因此該方法不會觸發
-(IBAction)BtnClick:(id)sender
{
NSLog(@"BtnClick");
}
將函數設為IBAction並從nib btn引用此函數。 在這種情況下,您無需顯式添加目標。
如果您沒有在筆尖中添加按鈕,那么不要忘記初始化並將其添加到視圖中
您可以查看本教程http://www.idev101.com/learn/interface_builder_connections.html
編輯檢查什么是打印?
for (UIButton *but in [self.view subviews])
{
NSLog("but.tag %d",but.tag);
if(but.tag==1)// compare for same row elements
{
NSLog("Button Added");
[btn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
}
您可以添加這樣的按鈕。 將此添加到您的didLoad方法
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:1];
[aButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
// then ...
- (void)buttonClicked:(UIButton*)button
{
NSLog(@"Button %d clicked.", [button tag]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.