Как программно установить фиксированный размер ImageView внутри TableViewCell? - PullRequest
0 голосов
/ 13 февраля 2020

У меня есть проблема, из-за которой мне нужно исправить размер изображения внутри ячейки таблицы. Изображение ниже показывает, что размер изображения не является равномерным.

image

Вот коды, которые я использовал.

 if noteImageIsAvailable == true {
        if let imageData = assignedNotePhoto?.photoData {
            if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
                //added fix
                cell.imageView?.frame.size = CGSize(width: 36, height: 24)
                cell.imageView?.clipsToBounds = true
                //-----
                cell.imageView?.contentMode = .scaleAspectFill
                cell.imageView?.image = image
            }
        }
    }

Я прочитал ответ здесь в stackoverflow. Он говорит, что мне нужно добавить clipToBounds, но, к сожалению, это не работает. Пожалуйста, помогите мне решить эту проблему. Спасибо

Код TableView

extension SettingNoteViewController: UITableViewDataSource, UITableViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return Menu.SettingNote.items.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "reuseIdentifier")
    let keyPass = KeyHelper.NoteSetting.info[indexPath.row]
    let assignedNotePhoto = self.getNotePhoto(key: keyPass.key)
    let assignedNoteTextData = self.getNoteTextData(key: keyPass.key)?.value

    cell.contentView.backgroundColor = .black
    cell.textLabel?.textColor = .white
    cell.detailTextLabel?.textColor = .white
    cell.detailTextLabel?.numberOfLines = 0
    let noteImageIsAvailable = assignedNotePhoto?.photoData != nil

    if noteImageIsAvailable == true {
        if let imageData = assignedNotePhoto?.photoData {
            if let image = Utilities.resizePictureImage(UIImage(data: imageData as Data)) {
                //added fix
                cell.imageView?.translatesAutoresizingMaskIntoConstraints = false
                cell.imageView?.frame.size = CGSize(width: 36, height: 24)
                cell.imageView?.clipsToBounds = true
                //-----
                cell.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
                cell.imageView?.image = image
            }
        }
    }
    cell.textLabel?.text = Menu.SettingNote.items[indexPath.row].value
    cell.detailTextLabel?.text = assignedNoteTextData ?? "noteSettingSubTitle".localized

    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.destination is InputMemoViewController {
        let vc = segue.destination as! InputMemoViewController
        vc.infoNoteKey = self.infoNoteKeyToPass
        vc.infoLabelText = self.infoLabelToPass
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.infoNoteKeyToPass = KeyHelper.NoteSetting.info[indexPath.row].key
    self.infoLabelToPass = KeyHelper.NoteSetting.info[indexPath.row].label
    self.performSegue(withIdentifier: "showInputMemo", sender: self)
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
   return 80
   }
}

Изображение ниже было выводом, когда я применил решение @Kishan Bhatiya. output

Первое и второе изображения - пейзажная фотография, а третье изображение - портретное output2

Ответы [ 2 ]

1 голос
/ 13 февраля 2020

Когда вы добавляете cell.imageView?.translatesAutoresizingMaskIntoConstraints = false, тогда frame не имеет никакого эффекта, поэтому попробуйте использовать любой из них

    let marginguide = contentView.layoutMarginsGuide


    //imageView auto layout constraints

    cell.imageView?.translatesAutoresizingMaskIntoConstraints = false

    let marginguide = cell.contentView.layoutMarginsGuide

    cell.imageView?.topAnchor.constraint(equalTo: marginguide.topAnchor).isActive = true
    cell.imageView?.leadingAnchor.constraint(equalTo: marginguide.leadingAnchor).isActive = true
    cell.imageView?.heightAnchor.constraint(equalToConstant: 40).isActive = true
    cell.imageView?.widthAnchor.constraint(equalToConstant: 40).isActive = true

    cell.imageView?.contentMode = .scaleAspectFill
    cell.imageView?.layer.cornerRadius = 20 //half of your width or height

И лучше установить ограничения в UITableViewCell

1 голос
/ 13 февраля 2020

У меня такая же проблема, scaleAspectFit для меня решено. Вы можете попробовать это

cell.imageView.contentMode = UIViewContentMode.scaleAspectFit
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...