Swift: элементы строки UITableView не скрываются при скрытии этой строки - PullRequest
0 голосов
/ 20 марта 2020

У меня есть класс табличного представления и три класса ячеек, которые я использую для заполнения 3 строк табличного представления. снимок экрана с моим табличным представлением

Я хочу скрыть 2-ю строку при каждом переключении Кнопка выключена. когда я нажимаю на кнопку переключения, строка сворачивается, но элемент ячейки не скрывается. скриншот после нажатия кнопки переключения

вот мой код:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row==0{
            let cell=tableView.dequeueReusableCell(withIdentifier: "cellid", for: indexPath) as! toggleCell
            return cell

        }
        if indexPath.row==1{
            let cell1=tableView.dequeueReusableCell(withIdentifier: "cellid2", for: indexPath) as! oneButtonCell
            cell1.layer.backgroundColor=UIColor.purple.cgColor
            return cell1
        }
        else{
            let cell1=tableView.dequeueReusableCell(withIdentifier: "cellid1", for: indexPath)
            cell1.layer.backgroundColor=UIColor.green.cgColor
            return cell1
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row==1{
            if istoggleOn==true{
                return 75
            }
            else{
            return 0
            }
        }
        else{
            return 75
        }
    }
}
class CellBase: UITableViewCell{
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style:style,reuseIdentifier:reuseIdentifier)
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupViews(){
        backgroundColor=UIColor.green
    }
}
class toggleCell:CellBase{

    let containerView=UIView()
    let label:UILabel={
        let label=UILabel()
        label.text="Toggle Button"
        label.textColor = .black
        label.font=UIFont.init(name: "HelveticaNeue-Bold", size: 20)
        return label
    }()
    lazy var button:UISwitch={
            let toggle=UISwitch()
            toggle.isOn=true
            toggle.onTintColor=UIColor(red: 59/255, green: 178/255, blue: 250/255, alpha: 1)
            toggle.addTarget(self, action: #selector(handleToggleAction), for: .valueChanged)
            return toggle
        }()
    @objc func handleToggleAction(sender:UISwitch){
         let parent = self.parentViewController as! ViewController

        if sender.isOn{
            print("on")
            parent.istoggleOn=true
            parent.tableView.beginUpdates()
            parent.tableView.endUpdates()
        }
        else{
            print("off")
            parent.istoggleOn=false
            parent.tableView.beginUpdates()
            parent.tableView.endUpdates()
        }
    }
    override func setupViews(){
    addSubview(containerView)
    setupContainerView()

    addConstraintsWithFormat(format: "H:|-20-[v0]-20-|", views: containerView)
    addConstraintsWithFormat(format: "V:|-15-[v0]-15-|", views: containerView)
}
    func setupContainerView(){
}
class oneButtonCell:CellBase{
    let containerView:UIView={
        let view=UIView()
        view.layer.cornerRadius=10
        view.layer.borderColor=UIColor(red: 59/255, green: 178/255, blue: 250/255, alpha: 1).cgColor
        view.layer.borderWidth=2
        return view
    }()
    let label:UILabel={
        let label=UILabel()
        label.text="SomeText"
        label.textColor = .black
        label.font=UIFont.init(name: "HelveticaNeue-Bold", size: 20)
        return label
    }()
    lazy var button:UIButton={
           let button=UIButton()
            button.setTitle("Button", for: .normal)
            button.titleLabel?.font=UIFont.init(name: "HelveticaNeue-Bold", size: 20)
            button.titleLabel?.adjustsFontSizeToFitWidth = true
            button.titleLabel?.minimumScaleFactor = 0.5
            button.setTitleColor(UIColor(red: 59/255, green: 178/255, blue: 250/255, alpha: 1), for: .normal)
            let image=UIImage(named: "arrow")?.withRenderingMode(.alwaysTemplate)
            button.setImage(image, for: .normal)
            button.imageView?.tintColor = .gray
            button.semanticContentAttribute = .forceRightToLeft
            button.addTarget(self, action: #selector(preferenceMenu), for: .touchUpInside)
            return button
        }()
    @objc func preferenceMenu(sender:UIButton){
        print("drop")
    }
    override func setupViews(){
        addSubview(containerView)
        setupContainerView()

        addConstraintsWithFormat(format: "H:|-20-[v0]-20-|", views: containerView)
        addConstraintsWithFormat(format: "V:|-15-[v0(45)]-15-|", views: containerView)
    }
    func setupContainerView(){
}
}

Я делаю все программно. пожалуйста, помогите мне, как я могу достичь этого

1 Ответ

0 голосов
/ 20 марта 2020

Содержимое ячейки отображается, потому что вы установили высоту строки 0 ... но этот подход к отображению / скрытию строки (и способу настройки ваших представлений) не меняет content этой ячейки.

Итак, содержимое все еще показывает , поскольку оно выходит за пределы ячейки.

Есть другие (возможно, лучшие) способы показать / скрыть строки, но придерживаться вашего подхода ...

Измените setupViews() веселье c в class CellBase на:

func setupViews(){

    // add this line
    self.clipsToBounds = true

    backgroundColor=UIColor.green

}

Редактировать

Поскольку код из исходного поста не был полным, я забыл заметить, что каждый пользовательский класс ячейки, вероятно, должен включать вызов super в его setupViews() fun c:

override func setupViews(){
    // adding this line will allow you to put common setup tasks
    // in the setupViews() func in CellBase class
    super.setupViews()

    // do additional setup tasks that are specific to this cell class
    addSubview(containerView)
    setupContainerView()

    addConstraintsWithFormat(format: "H:|-20-[v0]-20-|", views: containerView)
    addConstraintsWithFormat(format: "V:|-15-[v0]-15-|", views: containerView)
}
...