如何在NSMutableArray中添加UITextView作为对象



我正在尝试添加uitextview作为uitabaleview的单元格的子视图,为此,我在cellForRowAtIndex中以编程方式创建uitextview,我希望它能够从nsmutablearray动态显示文本到uitextview,然而问题是……如何区分不同的uitextview的特定单元格。我的代码是这样的.......

- (UITableViewCell *)tableView:(UITableView *)tv
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier=@"cell";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
 {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    @try{
    // Set up the cell...
    if (tv == self.smsTableView) {
        int count1=[smsTxt count];
        int rowCount=indexPath.row;
    int index1=(count1-(rowCount+1));
        NSLog(@"count:::%d",count1);
        NSLog(@"row count:::%d",rowCount);
        NSString *cellValueSMSTxt = [self.smsTxt objectAtIndex:index1];
        UITextView *msgView=[[UITextView alloc]init];
        msgView.frame=CGRectMake(12, 15, 280, 45);
        msgView.font=[UIFont systemFontOfSize:12.0];
        msgView.editable=FALSE;
        msgView.textColor=[UIColor grayColor];
        msgView.backgroundColor=[UIColor clearColor];
        msgView.text=cellValueSMSTxt;
        arrMsgView=[[NSMutableArray alloc]init];
        [arrMsgView addObject:msgView];
        [msgView release];
        UITextView *tempTextView=[arrMsgView objectAtIndex:rowCount];
        NSLog(@"countforarr:::%d",[arrMsgView count]);
        [cell.contentView addSubview:tempTextView];
        [arrMsgView release];
    }
    }@catch (NSException *e) {
        NSLog(@"%@",e);

    }

你可以通过子类化UITableViewCell并保持指针指向不同的UITextView来区分,或者通过在UITextView上设置一个标签(标签是一个UIView属性):

@property(nonatomic) NSInteger tag

现在你正在创建一个数组来保存uitextview并销毁它,这并没有让你走得太远。

 arrMsgView=[[NSMutableArray alloc]init];
 [arrMsgView addObject:msgView];
 [msgView release];
 UITextView *tempTextView=[arrMsgView objectAtIndex:rowCount];
 NSLog(@"countforarr:::%d",[arrMsgView count]);
 [cell.contentView addSubview:tempTextView];
 [arrMsgView release];

要访问给定的UITextView,你可以做的是在contentView子视图中循环查找给定的对象:

for (UIView* v in [contentView subviews]) {
    if ([v isKindOfClass:[UITextView class]] && v.tag == someIdTag) {
        // do something
    }
}

在这种情况下,您根本不需要额外的数组(subviews对象是一个数组)。

最新更新