简体   繁体   中英

swift : TableView cell size changing on run time

I am adding UIStackView inside the TableView cell. A custom class is created for UIStackView (MultipleChoice.swift) which have a button to add new options. In table view cell when I am clicking on the add option button, an option increase I want to expend the height of table view cell. As my add option button function is inside the MultipleChoice.swift how to update the height of the cell. This is table view controller initial cell When add button is pressed new option is added but the cell height is small to fit the newly added option Table view controller

    import UIKit

class ShowTableViewController: UITableViewController {
    //MARK Properties
    var items = [UIStackView]()

    override func viewDidLoad() {
        super.viewDidLoad()

        loadSample()

        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return items.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "EntityTableViewCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? EntityTableViewCell  else {
            fatalError("The dequeued cell is not an instance of MealTableViewCell.")
        }

        // Fetches the appropriate meal for the data source layout.
        let item = items[indexPath.row]
        cell.heightAnchor.constraint(equalToConstant: item.frame.height).isActive = true
        cell.cellStack.addArrangedSubview(item)
        return cell
    }


    func loadSample(){
        let item1 = ShortAnswer()
        let item2 = LongAnswer()
        let item3 = MultipleChoice()
        items += [item3]
    }
}

This is custom stack view class in this class add button function is mention as func addnewOption(button: UIButton)

import UIKit

@IBDesignable class MultipleChoice: UIStackView {
    //MARK: Properties
    var buttonTitle: String = "ADD"
    var optionsList = [UIStackView]()
    let options = QuestionsOptionsControl()
    let circleWidth:CGFloat = 31.5
    let circleHeight:CGFloat = 31.5
    //MARK : Initilazation
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.borderColor = UIColor.blue.cgColor
        self.spacing = 8
        self.axis = .vertical
        setItems()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        self.layer.borderColor = UIColor.blue.cgColor
        self.spacing = 8
        self.axis = .vertical
        setItems()
        //fatalError("init(coder:) has not been implemented")
    }


    func deleteOption(option: UIButton){
        removeArrangedSubview(option.superview!)
        option.superview!.removeFromSuperview()
        let items = arrangedSubviews
        let count = items.count
        if count == 6 {
            if let option = items[2] as? UIStackView{
                if  let hideDeleteButton = option.arrangedSubviews[2] as? UIButton{
                    hideDeleteButton.isHidden = true
                }
            }
        }
    }
    func addnewOption(button: UIButton){

        let bundle = Bundle(for: type(of: self))
        let multiChoiceNormal = UIImage(named:"multiChoiceNormal", in: bundle, compatibleWith: self.traitCollection)
        let delete = UIImage(named:"trashNormal", in: bundle, compatibleWith: self.traitCollection)

        let optionStack = UIStackView()

        let circle = UIImageView()
        circle.image = multiChoiceNormal
        circle.widthAnchor.constraint(equalToConstant: circleWidth).isActive = true
        circle.heightAnchor.constraint(equalToConstant: circleHeight).isActive = true

        let shortAnswer = UITextField()
        shortAnswer.placeholder = "Short answer text "

        let deleteButton = UIButton()
        deleteButton.setImage(delete, for: .normal)
        deleteButton.widthAnchor.constraint(equalToConstant: circleWidth).isActive = true
        deleteButton.addTarget(self, action: #selector(MultipleChoice.deleteOption(option:)), for: .touchUpInside)
        optionStack.addArrangedSubview(circle)
        optionStack.addArrangedSubview(shortAnswer)
        optionStack.addArrangedSubview(deleteButton)
        optionsList.append(optionStack)
        let itemsTotal = arrangedSubviews
        let index = (itemsTotal.count - 3)
        //addArrangedSubview(optionStack)
        insertArrangedSubview(optionStack, at: index)
        let items = arrangedSubviews
        let count = items.count
        if count == 6 {
            deleteButton.isHidden = true
        }
        else if count > 6{
            if let option = items[2] as? UIStackView{
                if  let hideDeleteButton = option.arrangedSubviews[2] as? UIButton{
                    hideDeleteButton.isHidden = false
                }
            }
        }

    }

    //MARK: Private
    private func setItems() {
        backgroundColor = UIColor.red

        //seprator
        let separator = UIView()
        separator.heightAnchor.constraint(equalToConstant: 1).isActive = true
        separator.backgroundColor = .black

        let newseparator = UIView()
        newseparator.heightAnchor.constraint(equalToConstant: 1).isActive = true
        newseparator.backgroundColor = .black
        //newseparator.widthAnchor.constraint(equalTo: separator.widthAnchor, multiplier: 0.6).isActive = true
        let question = UITextField()
        question.placeholder = "Question"
        addArrangedSubview(question)
        // newseparator.widthAnchor.constraint(equalTo: question.widthAnchor, multiplier: 1.6).isActive = true
        addArrangedSubview(newseparator)

        let addNewOptionButton = UIButton()
        addNewOptionButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
        //addNewOptionButton.setImage(multiChoiceHighlighted, for: .normal)
        addNewOptionButton.setTitle(buttonTitle , for: .normal)
        addNewOptionButton.widthAnchor.constraint(equalToConstant: 80).isActive = true
        addNewOptionButton.backgroundColor = UIColor.blue
        addNewOptionButton.addTarget(self, action: #selector(MultipleChoice.addnewOption(button:)), for: .touchUpInside)
        addArrangedSubview(addNewOptionButton)
        //seprator
        addArrangedSubview(separator)
        addArrangedSubview(options)
        addnewOption(button: addNewOptionButton)

    }

    func setButtonTitle(title: String){
        let items = arrangedSubviews
        let index = items.count
        guard let button = items[index-3] as? UIButton else{
            return
        }
        button.setTitle(title, for: .normal)

    }
    func hideOptions(){
        let items = arrangedSubviews
        let index = items.count
        guard let option = items[index-1] as? UIStackView else{
            return
        }
        option.isHidden = true
        items[0].isHidden = true
    }
}    

you can use :

    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

}

or if you want you cann add that "Add" button as a footer for row.

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