Текст UITextView иногда не заполняет все пространство в TableViewCell - PullRequest
0 голосов
/ 03 августа 2020

Я извлекаю данные из Twitter API и настраиваю ячейки таблицы так, чтобы они содержали UITextView для отображения твита. У меня возникает проблема, когда текст иногда занимает лишь небольшую часть доступного места перед переносом, как на этом изображении:

Image showing the problem

But if I go click back on the navigation controller, then reload the data it works as it should:

This is what it should look like

Can anyone explain why this is happening? Here is how my table view is set up:

    func numberOfSections(in tableView: UITableView) -> Int {
        if let tweets = timeline?.tweets {
            return 1
        }
        return 0
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if timeline == nil  {
            return 0
        } else {
            if let _timeline = timeline {
                return _timeline.tweets!.count
            }
        }
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.TweetTableViewCell, for: indexPath) as! TweetTableViewCell
            
        if let _timeline = timeline {
            
            if let tweet = _timeline.tweets?[indexPath.row] {
                cell.tweet = tweet
                cell.tweetTextView.translatesAutoresizingMaskIntoConstraints = true
                cell.tweetTextView.sizeToFit()
                cell.tweetTextView.isScrollEnabled = false
            }
        }
        
        return cell
    }

And this is my TableViewCell:

  class TweetTableViewCell: UITableViewCell {

    
    @IBOutlet weak var profileImageView: UIImageView!
    @IBOutlet weak var profileNameLabel: UILabel!
    @IBOutlet weak var profileTwitterUsername: UILabel!
    @IBOutlet weak var tweetTextView: UITextView!
    @IBOutlet weak var tweetDateLabel: UILabel!
    @IBOutlet weak var tweetTimeLabel: UILabel!
    @IBOutlet weak var mediaImageView: UIImageView!
    @IBOutlet weak var likesCountLabel: UILabel!
    

    var tweet: Tweet? {
        didSet {
            self.updateUI()
        }
    }
    
    func updateUI() {
        if let tweet = tweet {
            
            mediaImageView.isHidden = true

            let profileImageOriginalSizeUrl = tweet.user.profile_image_url_https.replacingOccurrences(of: "_normal", with: "")
            
            if let profileImageOriginalSizeUrl = URL(string: profileImageOriginalSizeUrl) {
                profileImageView.sd_setImage(with: profileImageOriginalSizeUrl, completed: nil) // Get image from cache
            }
            
            roundProfileImage()
           
            profileNameLabel.text = tweet.user.name
            profileTwitterUsername.text = "@\(tweet.user.screen_name)"
 
            tweetTextView.textContainerInset = UIEdgeInsets.zero
            tweetTextView.text = tweet.full_text
            
            tweetDateLabel.text = truncateDate(withDate: tweet.created_at)
            
            tweetTimeLabel.text = truncateTime(withDate: tweet.created_at)
        }

        if let media = tweet?.entities?.media?[0].media_url_https {
            
            mediaImageView.isHidden = false
            
            if let mediaImageUrl = URL(string: media) {
                mediaImageView.sd_setImage(with: mediaImageUrl, completed: nil)
            }
            
        }

    }

Also if it helps, here is my storyboard which contains the stack view holding the UITextView and UIImageView along with the constraints:

Раскадровка и ограничения

Консоль показывает некоторые из этих предупреждений, когда приложение запущено:

Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x7b140004a6a0 h=--& v=--& UITextView:0x7b740006d600'I'm back with a brand new...'.height == 95.5   (active)>",
    "<NSLayoutConstraint:0x7b1400045ba0 UITextView:0x7b740006d600'I'm back with a brand new...'.height == 100   (active)>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7b1400045ba0 UITextView:0x7b740006d600'I'm back with a brand new...'.height == 100   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
2020-08-03 04:57:43.373999+0100 StarChallenge[22459:10425072] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x7b140004a5b0 h=--& v=--& UITextView:0x7b740006d600'I'm back with a brand new...'.minX == 0   (active, names: '|':UIStackView:0x7b4c00045c80 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7b140004a600 h=--& v=--& UITextView:0x7b740006d600'I'm back with a brand new...'.width == 348.5   (active)>",
    "<NSLayoutConstraint:0x7b1400046e60 H:[UITextView:0x7b740006d600'I'm back with a brand new...']-(30)-|   (active, names: '|':UIStackView:0x7b4c00045c80 )>",
    "<NSLayoutConstraint:0x7b1400047040 H:|-(10)-[UIStackView:0x7b4c00045c80]   (active, names: '|':UITableViewCellContentView:0x7b4c00045ac0 )>",
    "<NSLayoutConstraint:0x7b1400047090 H:[UIStackView:0x7b4c00045c80]-(10)-|   (active, names: '|':UITableViewCellContentView:0x7b4c00045ac0 )>",
    "<NSLayoutConstraint:0x7b140004ae70 'fittingSizeHTarget' UITableViewCellContentView:0x7b4c00045ac0.width == 375   (active)>"
)

Ответы [ 2 ]

0 голосов
/ 03 августа 2020
"<NSAutoresizingMaskLayoutConstraint:0x7b140004a6a0 h=--& v=--& UITextView:0x7b740006d600'I'm back with a brand new...'.height == 95.5   (active)>",
    "<NSLayoutConstraint:0x7b1400045ba0 UITextView:0x7b740006d600'I'm back with a brand new...'.height == 100   (active)>"

Вы устанавливаете высоту ограничения вашего TextView = 100. И после отметок изменения размера высота ограничения составляет 95,5, что противоречит предыдущему значению.

  • Вы можете попробовать remove или установите приоритет высоты ограничения TextView на низкий (250).

Или используйте UILabel вместо этого, вам не нужно устанавливать высоту ограничения для метки и не также необходимо использовать AutoresizingMask и sizeToFit().

0 голосов
/ 03 августа 2020

Ваша ячейка завершила загрузку данных в розетки до завершения настройки автоматической компоновки.

Override layoutSubviews() {
Super.layoutSubviews
// Call your setup method
}

Это вызывается после того, как автоматическая компоновка делает это.

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