簡體   English   中英

ios小故障表視圖中的單元格圖像

[英]ios Glitches in table view cell image

我是Swift語言的新手...用圖像制作簡單表格,並希望在單元格內設置圖像視圖的角半徑。

代碼:-

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
}

不知道我在做什么錯,但是當我開始滾動表時,在顯示表時未設置拐角半徑... 在此處輸入圖片說明

編輯:-與cell.imageView?.layer.cornerRadius = 20得到很好的結果不知道為什么它與靜態值一起工作。

發生這種情況是由於ImageView在第一次加載tableView時仍未獲得Width或Height值。 您必須在Storyboard中的單元格內部傳遞imageView的Width和Height。

如果未傳遞Width或height,請在viewDidAppear方法中重新加載表格視圖。

您可以根據圖像中的建議在“單元格”中為“ ImageView”設置“約束”。

在此處輸入圖片說明

在此處輸入圖片說明

輸出:

在此處輸入圖片說明

創建像元時應用拐角半徑。

-(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;
}

如果要創建自己的imageView,最好在自定義TableViewCell中設置cornerRadius。

class CircularTableViewCell: UITableViewCell {
@IBOutlet weak var circularImageView: UIImageView!
override func layoutSubviews() {
    circularImageView.layer.cornerRadius = circularImageView.bounds.height / 2
    circularImageView.clipsToBounds = true
}

請注意,除非將imageView的寬高比設置為1:1,否則cornerRadius屬性不能保證視圖絕對是圓形的。 創建圓形視圖的另一種方法是使用蒙版。

您的代碼為真,但代碼排序錯誤

這是 :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM