2010-09-07 119 views
1

我已經創建了一個UIButton的子類,並希望將自定義屬性傳遞給它。然而,它不工作,我從那裏讀了一個UIButton子類化並不是一個好主意。UIButton的自定義屬性

我的問題是我如何分配一個自定義屬性到一個按鈕?我正在創建一個放在分組表的headerview中的按鈕。我想傳遞給該按鈕的節號。我已經在每行中使用UISwitch成功完成了這一操作,但不能對UIButton使用相同的方法。

所以我創建了一個按鈕

MattsButtonClass *button = [MattsButtonClass buttonWithType:UIButtonTypeCustom]; 
button.frame = CGRectMake(240, 15, 45, 30); 
button.MFsectionNo = section; //this would be 1, 2 etc 
//etc 

那麼,如何真正做到這一點?你會看到我的UIButton有一個子類,它看起來像這樣

//.h file 
@interface MattsButtonClass : UIButton { 
    int MFsectionNo; 
} 

@property (nonatomic) int MFsectionNo; 

@end 

//.m file 
@implementation MattsButtonClass 

@synthesize MFsectionNo; 


@end 

誤差以上是

-[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650 
2010-09-07 22:41:39.751 demo4[67445:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIRoundedRectButton MFsectionNo:]: unrecognized selector sent to instance 0x5673650' 

就是我想不可能?感謝您的幫助......

回答

5

你很可能只是使用的UIButtontag屬性來存儲你的節號(可能與偏移,因爲tag默認爲0)

+0

+1。簡單而有效的,如果一個普通的整數就足夠了 – Eiko 2010-09-07 22:15:30

+0

是的,這將工作 - 不知道爲什麼我沒有想到這一點。會告訴你這件事的進展的! – 2010-09-08 11:49:04

+0

完美運作。很簡單。也感謝其他人的選擇。 – 2010-09-08 11:54:49

2

這是不可能的,因爲你是使用函數調用:

[MattsButtonClass buttonWithType:UIButtonTypeCustom] 

該消息將返回一個UIButton 一個MattsButtonClass。這就是爲什麼該屬性不存在於返回的對象上。這使得UIButton很難繼承。然而,你也許能夠達到您想要的功能,通過以下:

MattsButtonClass *button = [[MattsButtonClass alloc] initWithFrame:CGRectMake(240, 15, 45, 30)]; 
button.MFsectionNo = section; 
0

也許記住這在每個節頭的按鈕引用數組?

 
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UIButton *myButton = [[UIButton alloc] init]; 
    [myButton addTarget:self action:@selector(myButton_touchUpInside:) forControlEvents:UIControlEventTouchUpInside]; 

    // previously defined as an instance variable of your viewcontroller 
    // NSMutableArray *sectionHeaderButtons; 
    [sectionHeaderButtons insertObject:myButton atIndex:section]; 
} 

然後在處理程序按鈕的TouchUpInside事件:

 
- (void)myButton_touchUpInside:(id)sender 
{ 
    int i; 
    for (i = 0; i < [sectionHeaderButtons count]; i++) 
    { 
     if ([sectionHeaderButtons objectAtIndex:i] == sender) 
      break; // now you know what section index was touched 
    } 
} 

如果觸摸按鈕的部分指標是你以後,這應該做的伎倆。

  1. 你重新安排的TableView部分,或
  2. 你已經有了部分

希望這有助於了很多:但是,如果不是最佳的。