TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Help. Only the last element is removed in UIScrollView 🙄

Forums > Swift

Good evening. I worked all the time on SwiftUI, I can’t figure out why the button only removes the last element from UIScrollView

[https://github.com/StevenKirke/-Test-Add-Child/blob/main/Test%20Add%20Child/ViewController.swift]()

class ViewController: UIViewController, UITextFieldDelegate {

    let custom: CustomElements = CustomElements()
    let child: CustomBlockChild = CustomBlockChild()

    let customGrey: UIColor = UIColor(named: "G_9b9b9b") ?? .black
    let customBlue: UIColor = UIColor(named: "B_01a7fd") ?? .black
    var size: CGFloat = .zero

    var childs: [UIStackView] = []

    var count: Int = 0

    var stackView: UIStackView = UIStackView()

    override func viewDidLoad() {

        self.size = view.frame.width

        let image = UIImage(systemName: "plus")?.withRenderingMode(.alwaysTemplate)

        let infoLabel = custom.createLabel(text: "Персональные данные", color: .black, weight: .medium)
        self.view.addSubview(infoLabel)

        let personPlaceHolder = custom.createLabel(text: "Имя", color: UIColor(named: "G_9b9b9b"), weight: .regular)
        let personName = custom.createLabel(text: "Петр", color: nil, weight: .semibold)

        let agePlaceHolder = custom.createLabel(text: "Возраст", color: UIColor(named: "G_9b9b9b"), weight: .regular)
        let personAge = custom.createLabel(text: "99", color: nil, weight: .semibold)

        let personNameVStack = custom.createVStack(elements: [personPlaceHolder, personName], color: customGrey)
        let personAgeVStack = custom.createVStack(elements: [agePlaceHolder, personAge], color: customGrey)

        self.view.addSubview(personNameVStack)
        self.view.addSubview(personAgeVStack)

        let infoChilds = custom.createLabel(text: "Дети (макс, 5)", color: .black, weight: .medium)
        let addChild = custom.createButton(text: "Добавить ребенка", image: image, color: customBlue)
        let addChildStack = custom.createHStack(elements: [infoChilds, addChild])
       // addChildStack.layer.borderWidth = 1
        self.view.addSubview(addChildStack)

        stackView.axis = .vertical
        stackView.layer.borderColor = UIColor.red.cgColor
        stackView.translatesAutoresizingMaskIntoConstraints = false
        //stackView.layer.borderWidth = 2

        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.width - 30, height: 2000))
        scrollView.layer.borderColor = UIColor.blue.cgColor
        //scrollView.layer.borderWidth = 1
        scrollView.translatesAutoresizingMaskIntoConstraints = false

//        for (index, element) in childs.enumerated() {
//            stackView.addArrangedSubview(child.createChild(size: size))
//        }

        childs.forEach { v in
            print("v")
            //stackView.addArrangedSubview(v)
         }

        scrollView.addSubview(stackView)
        self.view.addSubview(scrollView)

        let g = view.safeAreaLayoutGuide
             NSLayoutConstraint.activate([

                infoLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 20),
                infoLabel.leftAnchor.constraint(equalTo: g.leftAnchor, constant: 20),

                personNameVStack.topAnchor.constraint(equalTo: infoLabel.bottomAnchor, constant: 20),
                personNameVStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 18),
                personNameVStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -18),

                personAgeVStack.topAnchor.constraint(equalTo: personNameVStack.bottomAnchor, constant: 20),
                personAgeVStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 18),
                personAgeVStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -18),

                addChildStack.topAnchor.constraint(equalTo: personAgeVStack.bottomAnchor, constant: 0),
                addChildStack.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 18),
                addChildStack.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -18),

                scrollView.topAnchor.constraint(equalTo: addChildStack.bottomAnchor, constant: 0),
                scrollView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 18),
                scrollView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -18),
                scrollView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -200),

                stackView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0),
                stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 0),
                stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: 18),
                stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -18),

             ])

        addChild.addTarget(self, action: #selector(reloadScrollView), for: .touchUpInside)
    }

    @objc func buttonAction(sender: UIButton!) {
        //child.append(createChild(size: size))
        //print(child.count)
    }

    @objc func reloadScrollView() {
        //childs.append(child.insertNew(size: size))
        stackView.addArrangedSubview(child.insertNew(size: size, tag: count))
        count += 1
        print("\(childs.count)")
    }

}
class CustomBlockChild {

    let custom: CustomElements = CustomElements()

    let customGrey: UIColor = UIColor(named: "G_9b9b9b") ?? .black
    let customBlue: UIColor = UIColor(named: "B_01a7fd") ?? .black

    var childBlock: UIStackView = UIStackView()

    func createChild(size: CGFloat, tag: Int) -> UIStackView {
        let name = custom.createLabel(text: "Имя \(tag)", color: customGrey, weight: .regular)
        let nameField = custom.createTextField(tag: tag)
        let age = custom.createLabel(text: "Возраст", color: customGrey, weight: .regular)
        let ageField = custom.createTextField(tag: (tag + 10))
        let nameBlock = custom.createVStack(elements: [name, nameField], color: customGrey)
        let ageBlock = custom.createVStack(elements: [age, ageField], color: customGrey)
        let textFields = custom.createVStack(elements: [nameBlock, ageBlock], color: nil)

        textFields.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)

        let deleteButton = custom.createButtonDelete(text: "Удалить", color: customBlue, tag: tag)
        childBlock = custom.createHStack(elements: [textFields, deleteButton])
        childBlock.alignment = .top
        childBlock.tag = tag

        NSLayoutConstraint.activate([
            childBlock.widthAnchor.constraint(equalToConstant: (size - 40)),
            nameBlock.leadingAnchor.constraint(equalTo: childBlock.leadingAnchor, constant: 0),
            nameBlock.widthAnchor.constraint(equalToConstant: (size  / 2)),
        ])

        deleteButton.addTarget(self, action: #selector(deleteBlock), for: .touchUpInside)

        return childBlock
    }

    func insertNew(size: CGFloat, tag: Int) -> UIStackView {
       return createChild(size: size, tag: tag)
    }

    @objc func deleteBlock(sender: UIButton!) {
        switch childBlock.tag {
            case 0:
                if let viewWithTag = childBlock.viewWithTag(0) {
                    viewWithTag.removeFromSuperview()
                }else{
                    print("No!")
                }
                print("current tag - \(childBlock.tag)")
            case 1:
                if let viewWithTag = childBlock.viewWithTag(1) {
                    viewWithTag.removeFromSuperview()
                }else{
                    print("No!")
                }
            case 2:
                if let viewWithTag = childBlock.viewWithTag(2) {
                    viewWithTag.removeFromSuperview()
                }else{
                    print("No!")
                }
            case 3:
                if let viewWithTag = childBlock.viewWithTag(3) {
                    viewWithTag.removeFromSuperview()
                }else{
                    print("No!")
                }
            case 4:
                if let viewWithTag = childBlock.viewWithTag(4) {
                    viewWithTag.removeFromSuperview()
                }else{
                    print("No!")
                }
            default:
                print("OLOLO!")
        }

        /// childBlock.removeFromSuperview()
        //child.append(createChild(size: size))
        //print(child.count)
    }

}

3      

I did UITableView and custom UITableCell.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.