Круглое изображение в UITableViewCell - PullRequest
0 голосов
/ 16 мая 2018

Я пытаюсь создать круглые изображения внутри моего TableViewCell, но что-то идет не так. Я думаю, что cornerRadius слишком большой, потому что с этим кодом не отображается ни одно изображение. Если я, например, установлю значение cornerRadius на 30, я могу видеть изображения округленными, но не в виде четкого круга. Почему это не работает?

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "QuestionLine")
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "QuestionLine")


    let user = users[indexPath.row]
     cell?.textLabel?.text = user.question
     cell?.detailTextLabel?.text = user.name

     let image = UIImage(named: user.profilePicture)
     cell?.imageView?.image = image
     cell?.imageView?.layer.cornerRadius = (image?.size.width)! / 2
     cell?.imageView?.clipsToBounds = true

    return cell!

}

Ответы [ 3 ]

0 голосов
/ 22 мая 2018

Попробуйте этот код

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "QuestionLine")
    cell = UITableViewCell(style: .subtitle, reuseIdentifier: "QuestionLine")


    let user = users[indexPath.row]
    cell?.textLabel?.text = user.question
    cell?.detailTextLabel?.text = user.name

    let image = UIImage(named: user.profilePicture)
    cell?.imageView?.image = image

    cell?.imageView?.layer.cornerRadius = (cell?.imageView?.frame.size.width)! / 2
    cell?.imageView?.layer.masksToBounds = true
    cell?.imageView?.layer.borderColor = colour.cgColor
    cell?.imageView?.layer.borderWidth = 1

    return cell!
}
0 голосов
/ 22 мая 2018

Сначала убедитесь, что высота и ширина вашего изображения равны, а затем замените последние 3 строки кода на эти строки-

 cell?.imageView?.layer.cornerRadius = (image?.frame.size.width)!  /  2
 cell?.imageView?.masksToBounds = true

 return cell!
0 голосов
/ 22 мая 2018

Размер изображения в UITableViewCell будет соответствовать высоте ячейки. Если вы хотите настроить размер изображения, попробуйте следующий код.

   let image = UIImage(named: user.profilePicture)
    cell?.imageView?.image = image

    let itemSize = CGSize.init(width: 40, height: 40) // your custom size
    UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale);
    let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
    cell?.imageView?.image!.draw(in: imageRect)
    cell?.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!;
    UIGraphicsEndImageContext()

    cell?.imageView?.layer.cornerRadius = (itemSize.width) / 2
    cell?.imageView?.clipsToBounds = true
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...