Issues dynamically sizing collection view cell based on size of Tweet view with Swift iOS Kit

ios
swift

#1

Hi all,

For my application, I grab the most recent tweet of an account I’d like to display in my collection view cell and add it to my twitterView subview. However, I can’t seem to figure out a way to retrieve the height of my
the single Tweet prior to setting the height of my collection view cell in my UICollectionViewController.

In my sizeForItemAt function, I try to grab the height of twitter view by calling tweetView.frame.height for the height of my twitter row. This isn’t working and the default value is 25 instead of whatever the height of the tweet is. I believe this is because the height of the my tweet is set after I already make the cell, but I don’t know how to work around it (I was considering calling reloadData() in the collection view controller).

In the code I have below, I have a global variable for the tweetSize, but it doesn’t stay set unless I’m in the loadTweet instance which makes it so I can’t set the height of my cell in the view controller because the value doesn’t persist. For example, "print("In load tweet: “, self.getTweetSize())” prints the correct size, but "print("Tweet size is: “, tweetSize)” at the bottom of setupView() returns the default value which is (300, 25). I need the height of the cell to update dynamically because I want the view to look correct when my targeted account makes a new post.

I know it is bad practice to have all that code in the setupView(), but I would really like to get dynamic sizing working before I refactor my code. Any help or suggestions is greatly appreciated.

    var tweetSize:CGSize = CGSize()

    override func setupView() {
        addSubview(tweetView)
        addSubview(timelineButton)
        
        timelineButton.addTarget(self, action: #selector(displayTimeline), for: .touchUpInside)
        
        backgroundColor = .white
        NSLayoutConstraint.activate([
    
            tweetView.topAnchor.constraint(equalTo: topAnchor, constant: 15),
            tweetView.rightAnchor.constraint(equalTo: rightAnchor, constant: -15),
            tweetView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15),
            tweetView.bottomAnchor.constraint(equalTo: timelineButton.topAnchor, constant: -8),
            
            timelineButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 15),
            timelineButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -10),
        ])
        
        //Construct URL to query the most recent tweet from the featured event twitter account
        let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/user_timeline.json"
        let params = ["screen_name": "E3", "count": "1"]
        var clientError : NSError?
        
        let request = client.urlRequest(withMethod: "GET", urlString: statusesShowEndpoint, parameters: params, error: &clientError)
        
        client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
            if connectionError != nil {
                print("Error: \(connectionError)")
            }
            
            do {
                guard let data = data else { return }

                guard
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSArray,
                    let dict = json[0] as? NSDictionary,
                    let tweetID = dict["id_str"] as? String else { return }
                
                // Load the tweet in the Tweet view based on the ID retrieved
                self.client.loadTweet(withID: tweetID) { (tweet, error) in
                    if let t = tweet {
                        self.tweetView.configure(with: t)
                        self.setTweetSize(t:self.tweetView)
                        print("In load tweet: ", self.getTweetSize())
                    } else {
                        print("Failed to load Tweet: \(error?.localizedDescription)")
                    }
                }
            
            } catch let jsonError as NSError {
                print("json error: \(jsonError.localizedDescription)")
            }
        }
        
        tweetSize = tweetView.sizeThatFits(tweetView.frame.size)
        print("Tweet size is: ", tweetSize)
    }
    
    private func setTweetSize(t:TWTRTweetView ) -> Void {
        tweetSize = t.sizeThatFits(t.frame.size)
    }
    
    public func getTweetSize() -> CGSize {
        return tweetSize
    }

Thanks!