У меня есть функция, которая анимирует позицию y вида. Я вызываю эту функцию двумя способами: сначала как цель действия для кнопки, а во-вторых, наблюдая за уведомлением. В первом случае он работает, но во втором случае, когда он вызывается по уведомлению, он не анимируется. код функции:
func showResult() {
resultMode = true
self.containerView.frame.origin.y = CGFloat(1000)
self.view.layoutIfNeeded()
UIView.animate(
withDuration: 3,
animations: {
self.containerView.frame.origin.y = CGFloat(200)
self.view.layoutIfNeeded()
} ,
completion: nil
)
}
это называется:
NotificationCenter.default.addObserver(self, selector: #selector(self.showResult), name: NSNotification.Name(rawValue: "SHOWRESULT"), object: nil)
а также
resultBtn.addTarget(self, action: #selector(self.showResult), for: .touchUpInside)
В случае, если Notification вызовет этот showResult в основном потоке
@AhmadF Я добавил коды в вопрос
@PratikPrajapati! спасибо, сработало!





Тренировка модифицированного ниже метода showResult:
func showResult() {
resultMode = true
self.containerView.frame.origin.y = CGFloat(1000)
self.view.layoutIfNeeded()
DispatchQueue.main.async {
UIView.animate(
withDuration: 3,
animations: {
self.containerView.frame.origin.y = CGFloat(200)
self.view.layoutIfNeeded()
} ,
completion: nil
)
}
}
Попробуйте запустить уведомление в основном потоке
DispatchQueue.main.async {
NotificationCenter.default.addObserver(self, selector: #selector(self.showResult), name: NSNotification.Name(rawValue: "SHOWRESULT"), object: nil)
}
Причина:
Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
В моем случае у меня было закрытие при нажатии кнопки, при нажатии на которую нужно было оживить цвет. После нескольких часов разочарования вызов анимации внутри DispatchMain сработал
copyButton.buttonPressedAction = { [weak self] in
guard let self = self else {
return
}
DispatchQueue.main.async {
self.backgroundColor = .green
UIView.animate(withDuration: 2, animations: {() -> Void in
self.layer.backgroundColor = UIColor.clear.cgColor
})
}
}
Не могли бы вы добавить код двух случаев?