Я успешно создал расширение для UIViewController
, которое позволяет мне вызывать функцию, которая запускает UIView
анимацию вниз. Однако вместо простого UIView
я хочу улучшить расширение, чтобы оно принимало два параметра (background color
и label text
), которые являются подпредставлением для UIView
'popupAlert?
extension UIViewController {
func showAlert() {
let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
popupAlert.backgroundColor = UIColor.brandSuccess()
let window = (UIApplication.shared.delegate as! AppDelegate).window!
window.addSubview(popupAlert)
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
popupAlert.transform = .init(translationX: 0, y: 60)
}) { (_) in
UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
popupAlert.transform = .init(translationX: 0, y: -60)
}, completion: { (_) in
popupAlert.removeFromSuperview()
})
}
}
}
В данном методе нет текста
Да, я не уверен, куда поместить текст, он должен быть сосредоточен в UIView popupAlert. Имеет ли это смысл?
это очень плохая практика - изменять (то есть добавлять/удалять) подвиды экземпляра UIWindow
напрямую.
extension UIViewController {
func showAlert(bgColor: UIColor, lblText: String) {
let popupAlert = UIView(frame: CGRect(x: 0, y: -60, width: view.frame.width, height: 60))
let popupLbl = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 60))
popupAlert.backgroundColor = bgColor
popupLbl.text = lblText
popupLbl.textColor = .green
popupLbl.textAlignment = .center
let window = (UIApplication.shared.delegate as! AppDelegate).window!
popupAlert.addSubview(popupLbl)
window.addSubview(popupAlert)
UIView.animate(withDuration: 0.6, delay: 0, options: .curveEaseIn, animations: {
popupAlert.transform = .init(translationX: 0, y: 60)
}) { (_) in
UIView.animate(withDuration: 0.6, delay: 4, options: .curveEaseIn, animations: {
popupAlert.transform = .init(translationX: 0, y: -60)
}, completion: { (_) in
popupAlert.removeFromSuperview()
})
}
}
}
вызов
showAlert(bgColor: .red, lblText: "testtttt")
Спасибо, Бен, но как мне сделать так, чтобы lblText отображался в UIView?
@unicorn_surprise Вы должны добавить экземпляр UILabel
в popupAlert
Возможный дубликат Как хранить свойства в Swift так же, как в Objective-C?