I want to add a UILabel
to the view which slides down when an error occurs to send the error message to user and after 3 seconds it will slide up to disappear. The prototype of it is like the one Facebook or Instagram shows. I need errorLabel
in many ViewController
s, so I tried to subclass UILabel
. Here is my subclass ErrorLabel
:
class ErrorLabel: UILabel {
var errorString: String?
func sendErrorMessage() {
self.text = errorString
showErrorLabel()
let timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "hideErrorLabel", userInfo: nil, repeats: false)
}
func animateFrameChange() {
UIView.animateWithDuration(1, animations: { self.layoutIfNeeded() }, completion: nil)
}
func showErrorLabel() {
let oldFrame = self.frame
let newFrame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.height + 30, oldFrame.width)
self.frame = newFrame
self.animateFrameChange()
}
func hideErrorLabel() {
let oldFrame = self.frame
let newFrame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.height - 30, oldFrame.width)
self.frame = newFrame
self.animateFrameChange()
}
}
Then, I tried to add the errorLabel
to one of my ViewController
like following:
class ViewController: UIViewController {
var errorLabel = ErrorLabel()
override func viewDidLoad() {
super.viewDidLoad()
let errorLabelFrame = CGRectMake(0, 20, self.view.frame.width, 0)
self.errorLabel.frame = errorLabelFrame
self.errorLabel.backgroundColor = translucentTurquoise
self.errorLabel.font = UIFont.systemFontOfSize(18)
self.errorLabel.textColor = UIColor.whiteColor()
self.errorLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(errorLabel)
self.view.bringSubviewToFront(errorLabel)
}
func aFunc(errorString: String) {
self.errorLabel.errorString = errorString
self.errorLabel.sendErrorMessage()
}
}
When I run it in iOS Simulator, it doesn't work as expected:
errorLabel
shows on the left horizontally and in the middle vertically with onlyI...
which should beInvalid parameters
.- After 1 second, it goes to the position as expected but its width is still not
self.view.frame.width
. - After that, nothing happens but it should slide up after 3 seconds.
Can you tell me what's wrong and how to fix the error?
I might have partial solution to your issues. Hope it helps.
I...
happens when the string is longer than the view. For this you'll need to increase the size ofUILabel
.UIView.animateWithDuration
. Refer to this linkI suggest you to consider using
Extensions
to accomplish what you are trying to do.