создавать сенсорные тестовые приложения на Swift 4 или выше - PullRequest
0 голосов
/ 23 мая 2019

добрый день, я хочу сделать приложение для обнаружения касания на экране устройства ios (iphone). но я новичок в быстром

Я ожидаю, что когда открою приложение, интерфейс приложения будет похож на изображение, которое я прикрепил, и если я коснусь маленького квадрата, он исчезнет из интерфейса, а если я коснулся всего маленького квадрата, они исчезнут один одним. если все маленькие квадраты исчезнут, приложения покажут UIAlert успешным и завершат работу. Пожалуйста, помогите мне, и мне нужен ваш гид. благодарю вас Imgur изображение по ссылке я прикрепил

1 Ответ

0 голосов
/ 23 мая 2019

Вы можете использовать collectionview для создания макета. Используйте некоторый цвет для цвета ячейки по умолчанию. И когда ячейка представления коллекции выбрана, вы меняете цвет на прозрачный. Когда все ячейки выбраны, выдается предупреждение.

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

...