-2

I am trying to achieve a layout of a text followed by an image (image height calculated based on aspect ratio) then followed by text and so on. The issue is that the stackview that I am adding the views into randomly squash the views sometimes the imageviews disappear some time the text, it doesn't have a consistent behaviour.

i tried it on both uitableview and uicolletion view and the result is the same. is the combination of the mentioned views considered as a best practice for such usecase or not ? and if not what might be the best practice for such thing ?

class MyStackyView: UIStackView {

// Main variables
weak var videoPlayerDelegate: AVPlayerViewDelegate?
private var avVideoPlayersVC: [AVPlayerViewController] = []
var content: [Content]! {
    didSet {
        contentCombined = Utility.shared.combineToNew(contents: content)
    }
}
private var contentCombined: [Content] = [] {
    didSet {
        populatePostContent()
    }
}
var contentViews: [UIView] = []     // Holds the views created


override init(frame: CGRect) {
    super.init(frame: frame)
    configureView()
}

required init(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

deinit {
    print("DiaryPostView:: Deinitalized")
}

private func configureView() {
    axis = .vertical
    distribution = .fill
    alignment = .fill
    spacing = 0
}

}

// Extension to populate post content extension MyStackyView {

private func populatePostContent() {
    
    for content in contentCombined {
        if content.isMedia {
            addMedia(content)
        } else {
            addText(content.text)
        }
        
    }
    
}

}

// Extension to add the required views extension MyStackyView {

private func addText(_ text: String?, place: MediaPlace = .center) {
    
    let textView = generateDefaultTextView()
    //let parsedText = HTMLParser.shared.parseHTMLToAttributed(string: text ?? "") // fix font issue

    switch place {
        
        case .center:
            append(textView)
            contentViews.append(textView)
            
    }
    
    textView.text = text

        // لما استخدم ال parsedtext مرة النص بطلع مع الfont و مرة لا

}

private func addMedia(_ content: Content) {
    
    let avPlayerVC = getAVPlayerViewController()
    let mediaView = generateDefaultMediaView()
    
    switch content.getRawPlace() {
        case .center:
            append(mediaView)
            contentViews.append(mediaView)
            addText(content.text)
            NetworkManager().downloadMedia(content.img!, into: mediaView, avPlayerViewController: avPlayerVC) {
                
            }
            
        
            
    }
       
    
}

}

extension MyStackyView {

private func generateDefaultTextView() -> UILabel {
    let textView = UILabel()
    textView.backgroundColor = .clear
            
    textView.numberOfLines = 0
    textView.font = UIFont.customFont(.openSans, .regular, .title1, 17)

    return textView
}

private func generateDefaultHorizontalStack() -> UIStackView {
    let horizontalStack = UIStackView()
    horizontalStack.axis = .horizontal
    horizontalStack.distribution = .fill
    horizontalStack.alignment = .fill
    return horizontalStack
}

private func generateDefaultMediaView() -> MediaSliderView {
    let mediaSliderView = MediaSliderView()
    return mediaSliderView
}

private func getAVPlayerViewController() -> AVPlayerViewController? {
    videoPlayerDelegate?.getAVPlayerVC?()
}

func deallocateAVPlayers() {
    for player in avVideoPlayersVC {
        player.removeFromParent()
    }
    avVideoPlayersVC.removeAll()
}

}

i initalize a variable of the class in my uitableviewcell and then add these constraints

contentView.addSubview(MyStackyView)
    MyStackyView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8).isActive = true
    MyStackyView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8).isActive = true
    MyStackyView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16).isActive = true
    MyStackyView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16).isActive = true

please if possible, i need some guidance about this issue.

thank you, appreciate the help

VarDev
  • 1
  • 1
  • 1
  • Welcome to StackOverflow. Please take the [tour] and review [ask]. You need to provide more information about what you're doing... Is this a vertical or horizontal stack view? How do you have your constraints setup? Are you designing your cell as a Storyboard Prototype? If so, show that layout. If you're doing it via code, show your code. – DonMag Nov 08 '20 at 15:22
  • @DonMag thank you for replying, as you can see this is my first time asking a question on stackoverflow. now to answer your questions, it is a vertical stack view, now the constraints is only a height constraint set for my image view based on my aspect ratio calculations, and the label is set to numberOfLines to 0. now the view is created programmatically, i attached the code in the post for a reference point. thank you so much. – VarDev Nov 08 '20 at 17:35
  • @DonMag i have used a scrollview by it self with this stackview inside and it shows perfectly fine, this issue happens when i put the stackview inside the uitableviewcell or uicollectionviewcell. – VarDev Nov 08 '20 at 17:42
  • There is a lot in your code that is defined elsewhere (so we don't know what it is), and you have a LOT going on right now. I suggest starting simpler... create a cell with a vertical stack view, with a couple elements (a `UILabel` and a `UIImageView`, for example) and get that to work. Then start adding your your other elements and splitting code into extensions. As it is, too many unknowns. – DonMag Nov 08 '20 at 19:26
  • @DonMag great, so i will start with a simple stackview that has a text and imageview and will go from there. thank you, will keep you updated. hopefully things go well, thank you. – VarDev Nov 08 '20 at 22:55
  • @DonMag i have tested by adding a label then an image and it is giving me the same result, the image keeps squashing the label ?! any ideas why this is happening ? – VarDev Nov 09 '20 at 10:58

1 Answers1

0

Here is a (fairly) basic example.

We'll use a data structure like this:

struct VarDevStruct {
    var first: String = ""
    var second: String = ""
    var imageName: String = ""
}

The cell class has a vertical stack view containing:

  • multiline label
  • horizontal stack view
    • with an 80x80 image view and a label
  • multiline label

If any of the elements in the data struct are empty strings, we'll set the corresponding element in the cell to hidden.

First, the result:

enter image description here

after scrolling down to a few rows with different data:

enter image description here

and rotated:

enter image description here

Here's the complete code... plenty of comments in it, so it should be clear what the code is doing.


Data Structure

struct VarDevStruct {
    var first: String = ""
    var second: String = ""
    var imageName: String = ""
}

Cell class

class VarDevCell: UITableViewCell {
    
    let firstLabel = UILabel()
    let secondLabel = UILabel()
    let imgView = UIImageView()
    let imgNameLabel = UILabel()
    let vStack = UIStackView()
    let hStack = UIStackView()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    func commonInit() -> Void {
        
        // stack view properties
        vStack.axis = .vertical
        vStack.alignment = .fill
        vStack.distribution = .fill
        vStack.spacing = 8
        
        vStack.translatesAutoresizingMaskIntoConstraints = false
        contentView.addSubview(vStack)
        
        // let's use the default cell margins
        let g = contentView.layoutMarginsGuide
        
        NSLayoutConstraint.activate([
            // constrain stack view to all 4 sides
            vStack.topAnchor.constraint(equalTo: g.topAnchor),
            vStack.leadingAnchor.constraint(equalTo: g.leadingAnchor),
            vStack.trailingAnchor.constraint(equalTo: g.trailingAnchor),
            vStack.bottomAnchor.constraint(equalTo: g.bottomAnchor),
        ])
        
        // subview properties
        
        // background colors to make it easy to see the frames
        firstLabel.backgroundColor = .yellow
        secondLabel.backgroundColor = .green
        imgView.backgroundColor = .red
        imgNameLabel.backgroundColor = .cyan
        
        // multi-line labels
        firstLabel.numberOfLines = 0
        secondLabel.numberOfLines = 0
        
        imgNameLabel.textAlignment = .center
        
        // image view defaults to scaleToFill
        //  let's set it to scaleAspectFit
        imgView.contentMode = .scaleAspectFit
        
        // horizontal stack view
        hStack.axis = .horizontal
        hStack.alignment = .center
        hStack.distribution = .fill
        hStack.spacing = 8

        // add subviews to horizontal stack view
        hStack.addArrangedSubview(imgView)
        hStack.addArrangedSubview(imgNameLabel)
        
        // let's fill the vertical stack view with
        //  label
        //  hStack with 80x80 imageview and label with image name
        //  label
        vStack.addArrangedSubview(firstLabel)
        vStack.addArrangedSubview(hStack)
        vStack.addArrangedSubview(secondLabel)
        
        // set image view width and height
        imgView.widthAnchor.constraint(equalToConstant: 80.0).isActive = true
        imgView.heightAnchor.constraint(equalTo: imgView.widthAnchor, multiplier: 1.0).isActive = true

    }
    
    func fillData(_ vdStruct: VarDevStruct) -> Void {
        firstLabel.text = vdStruct.first
        secondLabel.text = vdStruct.second
        imgNameLabel.text = vdStruct.imageName
        
        // does our data have an image name?
        if !vdStruct.imageName.isEmpty {
            if #available(iOS 13.0, *) {
                if let img = UIImage(systemName: vdStruct.imageName) {
                    imgView.image = img
                }
            } else {
                // Fallback on earlier versions
                if let img = UIImage(named: vdStruct.imageName) {
                    imgView.image = img
                }
            }
        }
        
        // hide elements that we don't need in this cell
        firstLabel.isHidden = vdStruct.first.isEmpty
        secondLabel.isHidden = vdStruct.second.isEmpty
        hStack.isHidden = vdStruct.imageName.isEmpty
    }
    
}

Controller class

class VarDevTableViewController: UITableViewController {
    
    var myData: [VarDevStruct] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // register cell class for reuse
        tableView.register(VarDevCell.self, forCellReuseIdentifier: "cell")
        
        // generate some sample data
        myData = makeSampleData()
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        coordinator.animate(alongsideTransition: nil, completion: {
            _ in
            // make sure table re-calculates row heights
            UIView.setAnimationsEnabled(false)
            self.tableView.performBatchUpdates(nil, completion: nil)
            UIView.setAnimationsEnabled(true)
        })

    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! VarDevCell
        cell.fillData(myData[indexPath.row])
        return cell
    }
    
    func makeSampleData() -> [VarDevStruct] {
        var a: [VarDevStruct] = []
        
        // 15 sample data elements
        for i in 1...15 {
            let d = VarDevStruct(first: "This is the text for the first label in row: \(i).",
                                 second: "This will be a longer string to be used as the text for the second label in row \(i) (long enough to make sure we're getting some word wrapping).",
                                 imageName: "\(i).square.fill")
            a.append(d)
        }

        // change some of the sample data for variations
        //  (arrays are zero-based)
        
        // fifth row: no first label
        a[4].first = ""
        a[4].second = "This row has no First label text."
        
        // sixth row: no image
        a[5].first = "This row has no image."
        a[5].imageName = ""
        
        // seventh row: no second label
        a[6].first = "This row has no second label."
        a[6].second = ""
        
        // eigth row: no image or second label
        a[7].first = "This row has no image, and has no second label. The next row (9) has image only."
        a[7].imageName = ""
        a[7].second = ""
        
        // ninth row: image only
        a[8].first = ""
        a[8].second = ""
        
        // tenth row: first label with mutliple lines
        a[9].first = "One\nTwo\nThree\nFour"
        a[9].second = "This row has embedded newline chars in the text of the first label."

        return a
    }
    
}
DonMag
  • 69,424
  • 5
  • 50
  • 86
  • Great, i got it to work and all went great, thank you so much. What i was doing is that i was adding the label then when I have an image I append a UIView with an imageview inside, after the image loads from a network call i update the constraints on that view (the problem lays here thats why it was squeezing the other labels), thank you so much for your help, much appreciated. – VarDev Nov 10 '20 at 07:12