Круговой просмотр изображений изначально загружается как квадрат в UITableViewCell - Xamarin.iOS - PullRequest
0 голосов
/ 03 июня 2019

Я делаю мои 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;
    }

Моя проблема в том, что изначально это изображение загружается в виде квадратов, когда я прокручиваю только, оно превращается в круги. Как я могу решить эту проблему?

1 Ответ

0 голосов
/ 04 июня 2019

Это потому, что кадр 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 cell может выглядеть следующим образом:

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