UITableViewCell viewWithTag获取UIView框架的麻烦

时间:2013-09-02 13:09:32

标签: iphone ios uitableview custom-cell

我在故事板中UIView的自定义单元格中添加了UITableView,我就这样访问了它:

UIView *customView = (UIView *)[cell viewWithTag:CELL_CUSTOM_VIEW_TAG];
NSLog(@"%f", customView.frame.size.width);

但我的宽度为0.0000。我是以错误的方式访问它吗?

编辑: 这是我的完整cellForRow方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIImageView *customImageView = (UIImageView *)[cell viewWithTag:CELL_IMAGE_VIEW_TAG];
    customImageView.image = [UIImage imageNamed:@"foo.jpg"];
    //down is the code why I need the frame of it
    //I'm trying to make a right border to this UIImageView:
    CGRect imageViewFrame = customImageView.frame;
    CALayer *imageViewRightBorder = [self rightBorderWithColour:[UIColor blackColor] forView:imageViewFrame];
    [customImageView.layer addSublayer:imageViewRightBorder];

    return cell;
}

这是我的右边框到imageView的方法:

- (CALayer *)rightBorderWithColour:(UIColor *)color forView:(CGRect)viewFrame {
    CALayer *rightBorder = [CALayer layer];
    rightBorder.frame = CGRectMake(viewFrame.size.width, 0.0f, 1.0f, viewFrame.size.height);
    rightBorder.backgroundColor = [color colorWithAlphaComponent:1.0f].CGColor;
    return rightBorder;
}

1 个答案:

答案 0 :(得分:2)

我不明白你的逻辑。 cellForRowAtIndexPath是您定义UIView的地方,因此您拥有它。正如其他用户所说,向我们展示您的代码。

无论如何,这是我在我的tableview中定义的每个行中显示的自定义UIButton的方式。我假设你正在尝试做类似的事情。忘记将你的UIView添加到故事板。看看你是否可以使用此代码复制它。当然把它改成你的UIView代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

NSString *CellIdentifier = [NSString stringWithFormat:@"S%1dR%1d",indexPath.section,indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self
                   action:@selector(timerStopStart:)
         forControlEvents:UIControlEventTouchDown];
        [button setTitle:@"Start/Stop" forState:UIControlStateNormal];
        button.frame = CGRectMake(5.0f, 40.0f, 72.0f, 77.0f);
        button.tag = (indexPath.row)+100;
        [cell addSubview:button];

        //NSLog(@"number: %d ...", (indexPath.row)+100);
    }
}