swift 5 Как создать простейшую анимацию(маленькие кубики разлетаются в стороны от слова Поздравляю!)
Весь код:
import UIKit
class ViewController: UIViewController {
@objc func WordsCardValue(_ sender: UIButton) {
buttonWords2.isHidden = false
buttonWords.isHidden = true
countOfSuccesfulWords += 1
}
@objc func WordsCard(_ sender: UIButton) {
//Относится ли отправитель к кнопка коллекций
if buttonsMassive.contains(sender) {
senderIndex = buttonsMassive.firstIndex(of: sender)!
//Задача данных переменным
countOfWordsForDictionaryCheck = countOfWordsForDictionary[senderIndex]
namesCollectionForCardsLabel.text = namesForButtonCollection[senderIndex]
}
senderIndexCount = 0
senderIndexCountMin = 0
//Объявление главного словаря
if checkFirst {
if senderIndex == 0 {
countOfWordsForDictionaryCheckMin = 0
countOfWordsForDictionaryCheckMax = countOfWordsForDictionaryCheck*2
} else {
for i in countOfWordsForDictionary {
if senderIndex > senderIndexCount {
senderIndexCount += 1
senderIndexCountMin += i
} else {
countOfWordsForDictionaryCheckMin = senderIndexCountMin * 2
countOfWordsForDictionaryCheckMax = countOfWordsForDictionaryCheckMin + countOfWordsForDictionary[senderIndex]*2
break
}
}
}
}
if buttonsMassive.isEmpty != true {
wordCardToKeyButton()
countOfSuccesfulWordsLabel.text = String(countOfSuccesfulWords)
countOfSuccesfulWordsLabel.isHidden = false
namesCollectionForCardsLabel.isHidden = false
} else {
buttonMassiveEmpty()
}
}
func wordCardToKeyButton() {
buttonWords2.isHidden = true
if checkFirst {
for i in dictionaryCollections[countOfWordsForDictionaryCheckMin..<countOfWordsForDictionaryCheckMax] {
if check {
dictionaryKey.append(i)
dictionaryCollections.remove(at: dictionaryCollections.firstIndex(of: i)!)
check = false
} else {
dictionaryValue.append(i)
dictionaryCollections.remove(at: dictionaryCollections.firstIndex(of: i)!)
check = true
}
}
checkFirst = false
//На случай ошибки при вводе данных
if dictionaryKey.count < dictionaryValue.count {
countOfWordsMax = dictionaryKey.count
}
if dictionaryValue.count < dictionaryKey.count {
countOfWordsMax = dictionaryValue.count
}
if dictionaryKey.count == dictionaryValue.count {
countOfWordsMax = dictionaryKey.count
}
//
}
buttonWords.isHidden = false
//Создать копию buttonMassive
for i in buttonsMassive {
i.isHidden = true
}
if dictionaryKey.isEmpty {
wordCardEnd()
} else {
buttonWords.setTitle(dictionaryKey[0], for: .normal)
dictionaryKey.remove(at: 0)
if dictionaryValue.isEmpty {
wordCardEnd()
} else {
buttonWords2.setTitle(dictionaryValue[0], for: .normal)
dictionaryValue.remove(at: 0)
}
}
}
func wordCardEnd() {
checkFirst = true
congratulationsLabel.isHidden = false
buttonsMassive.remove(at: senderIndex)
countOfWordsForDictionary.remove(at: senderIndex)
namesForButtonCollection.remove(at: senderIndex)
countOfSuccesfulWordsLabel.isHidden = true
countOfSuccesfulWords = 0
buttonWords.isHidden = true
buttonWords2.isHidden = true
namesCollectionForCardsLabel.isHidden = true
congratulationsLabel.isHidden = true
for i in buttonsMassive {
i.isHidden = false
//Сделать функцию, чтобы правильно принимало размеры
}
if buttonsMassive.isEmpty {
buttonMassiveEmpty()
}
}
/*@objc func massLeave(_ sender: UIButton) {
countOfSuccesfulWordsCopy = countOfSuccesfulWords
countOfSuccesfulWordsLabel.isHidden = true
countOfSuccesfulWords = 0
buttonWords.isHidden = true
buttonWords2.isHidden = true
for i in buttonsMassive {
i.isHidden = false
//Сделать функцию, чтобы правильно принимало размеры
}
}*/
func buttonMassiveEmpty() {
checkFirst = true
countOfSuccesfulWordsLabel.isHidden = true
namesCollectionForCardsLabel.isHidden = true
buttonWords2.isHidden = true
randomElementForKeyAndValue = Int.random(in: 0..<dictionaryCollectionsCopy.count)
if randomElementForKeyAndValue % 2 == 0 {
buttonWords.setTitle(dictionaryCollectionsCopy[randomElementForKeyAndValue], for: .normal)
buttonWords2.setTitle(dictionaryCollectionsCopy[randomElementForKeyAndValue+1], for: .normal)
} else {
buttonWords.setTitle(dictionaryCollectionsCopy[randomElementForKeyAndValue-1], for: .normal)
buttonWords2.setTitle(dictionaryCollectionsCopy[randomElementForKeyAndValue], for: .normal)
}
buttonWords.isHidden = false
}
var namesForButtonCollection : [String] = ["fruits", "city", "clock"]
var countOfWordsForDictionary : [Int] = [4, 3, 2]
var check = true
var buttonNamesCheck = 0
var countOfWordsForDictionaryCheck = 0
var countOfWordsForDictionaryCheckMin = 0
var countOfWordsForDictionaryCheckMax = 0
var randomElementForKeyAndValue = 0
var countOfSuccesfulWords = 0
var countOfSuccesfulWordsCopy = 0
var countOfWordsMax = 0
var senderIndexCount = 0
var senderIndexCountMin = 0
var checkFirst = true
var buttonWords = UIButton()
var buttonWords2 = UIButton()
var senderIndex = 0
var leaveButton = UIButton()
let buttonsColumnSize : Int = Int(round(UIScreen.main.bounds.width / 2 - 30))
let buttonsColumnPlace2 : Int = Int(round(UIScreen.main.bounds.width / 2 + 10))
var buttonWordsSize : Int = Int(round(UIScreen.main.bounds.width)) - Int(round(UIScreen.main.bounds.width/10))
var buttonsMassive = [UIButton]()
var buttonsMassiveCopy = [UIButton]()
var namesCollectionForCardsLabel = UILabel()
var countOfSuccesfulWordsLabel = UILabel()
var congratulationsLabel = UILabel()
//Переделать на анимацию
var buttonCount = true
var dictionaryCollections : [String] = ["Apple", "Яблоко", "Grape", "Виноград", "Garnet", "Гранат", "Pear", "Груша", "Market", "Рынок", "House", "Дом", "Flat", "Квартира", "Ten", "Десять", "Clock", "Часы"]
var dictionaryCollectionsCopy : [String] = []
var dictionaryKey : [String] = []
var dictionaryValue : [String] = []
var dictionarySave = 0
override func viewDidLoad() {
super.viewDidLoad()
dictionaryCollectionsCopy = dictionaryCollections
buttonWords.frame.size = CGSize(width: buttonWordsSize, height: buttonWordsSize)
buttonWords.layer.cornerRadius = CGFloat(roundf(Float(buttonsColumnSize / 10)))
buttonWords.center = self.view.center
buttonWords.backgroundColor = .placeholderText
buttonWords.setTitleColor(.darkText, for: .normal)
buttonWords.addTarget(self, action: #selector(WordsCardValue(_ :)), for: .touchUpInside)
self.view.addSubview(buttonWords)
buttonWords.isHidden = true
buttonWords2.frame.size = CGSize(width: buttonWordsSize, height: buttonWordsSize)
buttonWords2.layer.cornerRadius = CGFloat(roundf(Float(buttonsColumnSize / 10)))
buttonWords2.center = self.view.center
buttonWords2.backgroundColor = .placeholderText
buttonWords2.setTitleColor(.darkText, for: .normal)
buttonWords2.addTarget(self, action: #selector(WordsCard(_:)), for: .touchUpInside)
self.view.addSubview(buttonWords2)
buttonWords2.isHidden = true
/*leaveButton.setImage(UIImage(named: "hit.png"), for: .normal)
leaveButton.addTarget(self, action: #selector(massLeave(_ :)), for: .touchUpInside)
leaveButton.frame = CGRect(x: 30, y: 30, width: buttonWordsSize, height: buttonWordsSize)
view.addSubview(leaveButton)*/
namesCollectionForCardsLabel.font = UIFont(name: "systemFont", size: round(UIScreen.main.bounds.width / 20))
namesCollectionForCardsLabel.backgroundColor = .clear
namesCollectionForCardsLabel.frame = CGRect(x: 0, y: 30, width: 100, height: 100)
namesCollectionForCardsLabel.center.x = self.view.center.x
countOfSuccesfulWordsLabel.font = UIFont(name: "systemFont", size: round(UIScreen.main.bounds.width / 20))
countOfSuccesfulWordsLabel.backgroundColor = .clear
countOfSuccesfulWordsLabel.frame = CGRect(x: 0, y: 400, width: 100, height: 100)
congratulationsLabel.font = UIFont(name: "systemFont", size: round(UIScreen.main.bounds.width / 10))
congratulationsLabel.backgroundColor = .clear
congratulationsLabel.frame = CGRect(x: 0, y: 30, width: 200, height: 300)
congratulationsLabel.center.x = self.view.center.x
congratulationsLabel.text = "Congratulations!"
createButtons()
view.addSubview(namesCollectionForCardsLabel)
view.addSubview(countOfSuccesfulWordsLabel)
view.addSubview(congratulationsLabel)
congratulationsLabel.isHidden = true
}
private func createButtons() {
buttonNamesCheck = 0
var y = 50
for i in 0..<namesForButtonCollection.count {
var buttonCollectionFrame = CGRect(x: 20, y: y, width: buttonsColumnSize, height: buttonsColumnSize)
var buttonCollectionFrame2 = CGRect(x: buttonsColumnPlace2, y: y, width: buttonsColumnSize, height: buttonsColumnSize)
let button = UIButton(type: .system)
if buttonCount {
button.frame = buttonCollectionFrame
buttonCount = false
} else {
button.frame = buttonCollectionFrame2
buttonCount = true
y += buttonsColumnSize + 20
}
button.backgroundColor = .gray
button.titleLabel?.textAlignment = .center
button.layer.cornerRadius = CGFloat(roundf(Float(buttonsColumnSize / 10)))
view.addSubview(button)
buttonsMassive.append(button)
buttonsMassiveCopy.append(button)
button.addTarget(self, action: #selector(WordsCard(_ :)), for: .touchUpInside)
}
for i in buttonsMassive[0..<namesForButtonCollection.count] {
i.setTitle(namesForButtonCollection[buttonNamesCheck], for: .normal)
buttonNamesCheck += 1
}
}
}
Не обязательно взаимодействовать с кодом, можно просто пример
Ответы (1 шт):
Автор решения: schmidt9
→ Ссылка
Пример простой анимации на основе частиц SpriteKit, основанный на данной статье
Создаем сцену и файл для работы с частицами, можно выбрать разные шаблоны при создании и поиграться с их настройками
Настраиваем сториборд
Связываем все в коде
import UIKit
import SpriteKit
class ViewController: UIViewController {
@IBOutlet var congratulationsLabel: UILabel!
@IBOutlet var particlesView: SKView!
var scene: SKScene? {
let scene = SKScene(fileNamed: "MyScene")
scene?.backgroundColor = .clear
return scene
}
override func viewDidLoad() {
super.viewDidLoad()
congratulationsLabel.isHidden = true
particlesView.backgroundColor = .clear
particlesView.allowsTransparency = true
// фикс для избавления от мерцания при загрузке
let emptyScene = SKScene()
emptyScene.backgroundColor = .clear
particlesView.presentScene(emptyScene)
}
func showCongratulations() {
congratulationsLabel.isHidden = false
particlesView.presentScene(scene)
}
@IBAction func runParticlesAnimationButtonTouchUpInside(_ sender: UIButton) {
showCongratulations()
}
}
...
Профит



