圆形图像视图最初在UITableViewCell - Xamarin.iOS中加载为正方形



我正在将我的UIImageView做成UITableViewCell中的圆圈。所以我在下面的GetCell方法中这样做了。

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
        UITableViewCell cell = tableView.DequeueReusableCell(_cellIdentifier);
        RemotesupportAgentData item = _tableItems[indexPath.Row];
        //---- if there are no cells to reuse, create a new one
        if (cell == null)
        {
            cell = new UITableViewCell(UITableViewCellStyle.Default, _cellIdentifier);
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
        }
        cell.TextLabel.Text = (string)item.Attributes["Name"];
        cell.ImageView.SetImage(new NSUrl((string)item.Attributes["avatar"]), UIImage.FromBundle("contacts-32.png"));
        cell.ImageView.ClipsToBounds = true;
        cell.ImageView.Layer.CornerRadius = cell.ImageView.Frame.Width / 2;
        cell.ImageView.Layer.BorderColor = UIColor.Green.CGColor;
        cell.ImageView.Layer.BorderWidth = (nfloat)2.0;
        return cell;
    }

我的问题是,最初当我滚动时,此图像视图加载为正方形,它只会使自己成为圆圈。我该如何解决这个问题?

这是因为cell.ImageView的帧在初始时间为零。在完成显示之前,它不会呈现为实际大小。

而且我不建议您将配置代码放在单元的重用方法中。当单元格出现时,将一遍又一遍地调用此事件。由于性能考虑,我们应该只将价值设置的东西放在该事件中。

因此,首先,创建一个新的表视图类并在那里进行一些配置:

public class MyCustomCell : UITableViewCell
{
    public MyCustomCell(IntPtr handle) : base(handle)
    {
        SelectionStyle = UITableViewCellSelectionStyle.None;
        ImageView.ClipsToBounds = true;   
        ImageView.Layer.BorderColor = UIColor.Green.CGColor;
        ImageView.Layer.BorderWidth = (nfloat)2.0;
    }
    public override void Draw(CGRect rect)
    {
        base.Draw(rect);
        // Your will get the actual size in the event
        if (ImageView.Layer.CornerRadius == 0)
            ImageView.Layer.CornerRadius = ImageView.Frame.Width / 2;
    }
}

然后,在初始化表视图时注册它:

tableView.Source = new MyTableViewSource(list);
tableView.RegisterClassForCellReuse(typeof(MyCustomCell), _cellIdentifier);

最后,您的get单元格方法可以简单地像这样:

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
    MyCustomCell cell = tableView.DequeueReusableCell(_cellIdentifier) as MyCustomCell;
    RemotesupportAgentData item = _tableItems[indexPath.Row];
    cell.TextLabel.Text = (string)item.Attributes["Name"];
    cell.ImageView.SetImage(new NSUrl((string)item.Attributes["avatar"]), UIImage.FromBundle("contacts-32.png"));
    return cell;
}

最新更新