简体   繁体   English

collectionview 或 uitableview 中的 Stackview

[英]Stackview inside collectionview or uitableview

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.我在 uitableview 和 uicolletion 视图上都试过了,结果是一样的。 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 { // 填充帖子内容的扩展扩展 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 { // 添加所需视图的扩展扩展 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 {扩展 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我在 uitableviewcell 中初始化类的变量,然后添加这些约束

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谢谢,感谢帮助

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带有 80x80 图像视图和标签
  • 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 .如果数据结构中的任何元素是空字符串,我们会将单元格中的相应元素设置为hidden

First, the result:首先,结果:

在此处输入图片说明

after scrolling down to a few rows with different data:向下滚动到具有不同数据的几行后:

在此处输入图片说明

and rotated:并旋转:

在此处输入图片说明

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
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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