Search code examples
swifttouchdetect

create touch test apps on swift 4 or above


good day, i want to make an app to detect touch in the screen of ios device (iphone). but i am new in swift

i expect, when open the app, the interface of app like the image i attached,and if i touch the small square one, it will be dissappear from interface, and if i have touced all small square, they will dissappear one by one. if all small square is dissapear, the apps will show UIAlert success and exit. please help me and i need your guide. thank you Imgur the image on the link i attached


Solution

  • You can use collectionview for creating the layout. Use some color for default collectionview cell color. And when a collection view cell is selected you change change the color to clear color. When all cells are selected present the alert.

    class ViewControllerNew: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
        let collectionView = CollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
        var arr = [Int]()
        var deletedArr = [Int]()
        var rowCount = 0
        override func viewDidLoad() {
            super.viewDidLoad()
            view.backgroundColor = .white
    
            collectionView.backgroundColor = .white
            collectionView.delegate = self
            collectionView.dataSource = self
            collectionView.translatesAutoresizingMaskIntoConstraints = false
            collectionView.register(Cell1.self, forCellWithReuseIdentifier: "Cell1")
            collectionView.isScrollEnabled = false
            view.addSubview(collectionView)
    
            collectionView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true
            collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
            collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
            collectionView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    
            if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
                let itemSpacing: CGFloat = 5
                let itemsInOneRow: CGFloat = 5
                layout.sectionInset = UIEdgeInsets(top: itemSpacing, left: itemSpacing, bottom: itemSpacing, right: itemSpacing)
                layout.minimumInteritemSpacing = itemSpacing
                layout.minimumLineSpacing = itemSpacing
                let cellWidth = (UIScreen.main.bounds.width - (itemSpacing * 2) - ((itemsInOneRow - 1) * itemSpacing)) / itemsInOneRow
                let rowCount = UIScreen.main.bounds.height / cellWidth
                let newRowCount = Int((UIScreen.main.bounds.height - (itemSpacing * 2) - ((rowCount - 1) * itemSpacing)) / cellWidth)
                layout.itemSize = CGSize(width: cellWidth, height: cellWidth)
                self.arr = Array(0..<newRowCount*Int(itemsInOneRow))
                collectionView.reloadData()
            }
        }
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return arr.count
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell1", for: indexPath)
            cell.backgroundColor = .red
            cell.isUserInteractionEnabled = true
            return cell
        }
        func updateCells(_ touches: Set<UITouch>) {
            guard let location = touches.first?.location(in: collectionView),
                    let indexPath = collectionView.indexPathForItem(at: location),
                    let cell = collectionView.cellForItem(at: indexPath) else {
                        return
            }
            cell.backgroundColor = .clear
            if !deletedArr.contains(indexPath.item) {
                deletedArr.append(indexPath.item)
            }
            if deletedArr.count == arr.count {
                let alert = UIAlertController(title: "Game Finished", message: nil, preferredStyle: .alert)
                let okBtn = UIAlertAction(title: "Ok", style: .default) { action in
                    self.deletedArr.removeAll()
                    self.collectionView.reloadData()
                }
                alert.addAction(okBtn)
                self.present(alert, animated: true, completion: nil)
            }
        }
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            updateCells(touches)
        }
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            updateCells(touches)
        }
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            updateCells(touches)
        }
    }
    class Cell1: UICollectionViewCell {
        override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            return nil
        }
    }
    class CollectionView: UICollectionView {
        override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            return nil
        }
    }
    

    enter image description here