2011-02-12 56 views
2


我有我的UITableViewCell子類中,我以這種方式使用的UISwitchaccessoryView
mySwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
self.accessoryView = mySwitch;
,一切都OK!該應用程序工作正常。

UISwitch在自定義accessoryView的

現在我需要添加一些UIImageView開關上面,所以我想:「好吧,讓我們做一個自定義accessoryView的!」:
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 10.0f, 100.0f, 60.0f)];
...
mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0.0f, 22.0f, 94.0f, 27.0f)];
[myView addSubview:mySwitch];
self.accessoryView = myView;
[myView release];

一切似乎是確定的,但有一個奇怪的行爲。當我打開另一個視圖控制器並回到桌面時,交換機被神祕地改變了......
這不是數據管理中的問題,而只是在單元格重繪中... 請幫助我,我該怎麼辦?

在此先感謝

回答

0

EMH ......我發現這個問題...這是不掛表重繪...
UIControlEventValueChanged選擇檢索開關值和細胞indexPath.row這種方式:
UISwitch *tempSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)[tempSwitch superview];

,然後將其更新相應的對象(一個數據邏輯類的)保存在NSMutableArray(在所述的tableview的數據源)

但是,現在的開關是不accessoryView的,但一個子視圖accessoryView的對象,所以對象在au中更新不可預知的方式。我解決了第二個superview消息。

對不起,我的錯誤,並感謝所有...

2

這是因爲細胞被重用。因此,如果您將子視圖添加到單元格的內容視圖中,然後在該單元格被重新用於另一行之後,該視圖將出現在該行中。避免這種情況的最好方法是將NSArray保存在表格的數據源中(通常是您的視圖控制器),其中包含所有自定義視圖(包含子視圖)。然後,你可以這樣做:

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath { 
    NSInteger row = indexPath.row; 
    static NSString* cellIdentifier = @"Trololo"; 

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier: cellIdentifier]; 
    if(!cell) {  
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier: cellIdentifier] autorelease]; 
    } 

    [[cell.contentView subviews] makeObjectsPerformSelector: @selector(removeFromSuperview)]; 
    [cell.contentView addSubview: [_your_cell_views objectAtIndex: row]]; 

    return cell; 
} 
+0

等待,`[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]`將刪除所有* *子視圖,包括文字標籤。所有你需要的是正確設置`accessoryView`。 – Costique 2011-02-12 10:41:41