kishan94 kishan94 - 4 years ago 410
Swift Question

ios Glitches in table view cell image

I am new to swift language...
Making simple table with image, and want to set corner radius of image view inside cell.

Code :-

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)!

cell.textLabel?.text = "Test"
cell.detailTextLabel?.text = "\(indexPath.row)"

if(cell.imageView != nil){
cell.imageView?.image = UIImage(named: "avatar")
cell.imageView?.layer.cornerRadius = cell.imageView!.frame.size.height/2
cell.imageView?.layer.masksToBounds = true

}


return cell
}


Don't know what i am doing wrong, but corner radius not seted when table display when i start to scroll table it set properly ...enter image description here

Edit:-
Getting fine result with
cell.imageView?.layer.cornerRadius = 20

Don't know why it works with static value.

Answer Source

This happens due to ImageView is still not getting Width or Height value at time tableView loading first time. You must have to pass Width and Height of imageView inside cell in Storyboard.

If you are not passing Width or height then reload table view in viewDidAppear method.

You can set Constraint for ImageView in Cell as suggested in image.

enter image description here

enter image description here

Output :

enter image description here

Apply Corner radius when creating cell.

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

static NSString *cellIdentifier = @"cell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}

UIImageView *imgView = (UIImageView *) [cell.contentView viewWithTag:9];

NSLog(@"Frame : %@", NSStringFromCGRect(imgView.frame));

imgView.layer.cornerRadius = imgView.frame.size.width/2.0;
imgView.layer.masksToBounds = YES;
//imgView.clipsToBounds = YES;

UILabel *lbl = (UILabel *)[cell.contentView viewWithTag:99];
if(indexPath.row % 2 == 0){

    lbl.text = [NSString stringWithFormat:@"Index : %ld -- I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....I am Even....",(long)indexPath.row];

}else{

    lbl.text = [NSString stringWithFormat:@"Index : %ld -- I am Odd....I am Odd....I am Odd....I am Odd....I am Odd....I am Odd....I am Odd....I am Odd....",(long)indexPath.row];

}
return cell;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download