Как установить NSLayoutConstraint в Swift? - PullRequest
0 голосов
/ 18 декабря 2018

Я хочу изменить некоторые ограничения в разных случаях.

Объявление моих ограничений из раскадровки:

    @IBOutlet weak var topConstraintPostImageView: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

Это мой код, в котором я хочу изменить ограничения:

func updateCellView(post: PostModel) {

    // Wenn Bild mit Text gepostet wird
    if post.imageURL != nil && post.postText != nil {

        topConstraintPostImageView.constant = 10

        // Wenn Text ohne bild gepostet wird
    } else if post.imageURL == nil && post.postText != nil  {

        heightConstraint.constant = 1

        // Wenn Bild ohne Text gepostet wird
    } else if post.imageURL != nil && post.postText == nil {

        topConstraintPostImageView.constant = 0

    }
}

Но ограничения по-прежнемуне меняется

Вот мой cellForRowAt func:

    extension DiscoveryViewController: UITableViewDataSource {
    // wie viele Zellen
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return postArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DiscoveryCollectionViewCell", for: indexPath) as! DiscoveryCollectionViewCell

        cell.updateCellView(post: postArray[indexPath.row].post!)
        cell.layoutIfNeeded()
        cell.user = postArray[indexPath.row]
        cell.post = postArray[indexPath.row]
        cell.delegate = self

        return cell
    }
}

enter image description here

Заранее спасибо за вашу помощь!

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

Подумайте о том, чтобы вызвать setNeedsUpdateConstraints() в вашем представлении из updateCellView(), а затем реализовать:

class MyView: UIView {
  // ...
  override func updateConstraints() {
    super.updateConstraints()
    // This is where you update your constraints including the logic above.
  }
  // ...
}

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

0 голосов
/ 18 декабря 2018

Вставьте cellForRowAt в vc

 cell.updateCellView(arr[indexPath.row])////  change arr to your datasource arr inside here set constants
 cell.layoutIfNeeded()
 return cell

в конце оператора if

...