简体   繁体   中英

How do I add a UIView to a UIStackView in a UITableViewCell?

Whenever I try to add an image, gif, or video to the StackView, the cell does not resize to fit the media. The media just overlaps everything inside the StackView.

class HubTableViewCell: UITableViewCell {

@IBOutlet weak var labelContent: UILabel!
@IBOutlet weak var stackViewContainer: UIStackView!

var mediaImage:UIImageView?

override func layoutSubviews() {
    super.layoutSubviews()
    mediaImage = UIImageView(frame: CGRect(x: 0, y: 0, width: stackViewContainer.bounds.width, height: 420))
    mediaImage?.kf_setImageWithURL(NSURL(string: "https://placem.at/people")!)
    mediaImage?.clipsToBounds = true
    mediaImage?.contentMode = .ScaleAspectFill
    mediaImage?.widthAnchor.constraintEqualToConstant(stackViewContainer.bounds.width).active = true
    mediaImage?.heightAnchor.constraintEqualToConstant(420).active = true
    if let mediaImage = mediaImage {
        stackViewContainer.insertSubview(mediaImage, aboveSubview: labelContent)
        stackViewContainer.bringSubviewToFront(mediaImage)
    }
}

override func prepareForReuse() {
    super.prepareForReuse()
    if let mediaImage = mediaImage {
        stackViewContainer.removeArrangedSubview(mediaImage)
        mediaImage.removeFromSuperview()
    }
    mediaImage = nil
}

 }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier") as! UITableViewCell
    cell.yourUIStackView.addArrangedSubview(yourView)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM