【问题标题】:swift : TableView cell size changing on run timeswift : TableView 单元格大小在运行时发生变化
【发布时间】:2018-04-06 14:54:11
【问题描述】:

我在 TableView 单元格中添加 UIStackView。为 UIStackView (MultipleChoice.swift) 创建了一个自定义类,其中有一个添加新选项的按钮。在表格视图单元格中,当我单击添加选项按钮时,我想增加一个选项以增加表格视图单元格的高度。由于我的添加选项按钮功能位于 MultipleChoice.swift 中,因此如何更新单元格的高度。 这是表视图控制器 initial cellWhen add button is pressed new option is added but the cell height is small to fit the newly added option 表格视图控制器

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

这是该类中的自定义堆栈视图类,添加按钮功能被提及为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
    }
}    

【问题讨论】:

  • 你可以使用ProtocolsDelegates或者你可以尝试NSNotification来达到你想要的效果。

标签: ios swift uitableview autoresize


【解决方案1】:

你可以使用:

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

}

或者,如果您愿意,也可以将该“添加”按钮添加为行的页脚。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多