0

I showing a subview which contains the a subview, an image and a message. I need to remove this subview after a particular duration/time (5 seconds) in swift. The code for the subviews is as follows:

     var HideView = UIView (frame: CGRectMake(0 , 0, 320, 480));
    HideView.backgroundColor = UIColor(red:0.0, green:0.0, blue:0.0, alpha:0.6);
    var ErrorView = UIView (frame: CGRectMake(0, 40, 320, 70));
    ErrorView.backgroundColor = UIColor(red:0.8, green:0.376, blue:0.094, alpha:1.0);
    ErrorView.clipsToBounds = true;
    ErrorView.layer.shouldRasterize = true
    HideView.addSubview(ErrorView)

    var ErrorImageView = UIImageView(frame: CGRectMake(5, 5, 30, 30));
    var ErrorImage = UIImage(named: "error_icon_white.pdf");
    ErrorImageView.image = ErrorImage;
    ErrorView.addSubview(ErrorImageView)

    var ErrorLabel = UILabel (frame: CGRectMake(50, 0, 270, 70));
    ErrorLabel.backgroundColor = UIColor.clearColor();
    ErrorLabel.textColor = UIColor.whiteColor()
    ErrorLabel.font =  UIFont(name: "Gotham", size: 1)
    ErrorLabel.numberOfLines = 3
    var errmsg = "Hello world"
    ErrorLabel.text = errmsg;
    ErrorView.addSubview(ErrorLabel)
    self.view.addSubview(HideView);

Can I achieve this requirement? If Yes then how? Thanks in advance.

Amit Raj
  • 1,200
  • 3
  • 17
  • 45

1 Answers1

1

After adding your subview, add a timer to fire after the desired period of time (5 seconds)

var timer = NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(5.0), target: self, selector: "timeExpired", userInfo: nil, repeats: false)

Then, you perform whatever action you like in the "timeExpired" function:

func timeExpired() {
        println("time expired")
        // yoursubview.removeFromSuperview()
    }
Istvan
  • 1,170
  • 1
  • 7
  • 8
  • Sorry lstvan, it does not work for me. 2015-04-28 17:11:02.755 testtool[6243:203754] -[testtool.ViewController timeExpired]: unrecognized selector sent to instance 0x79f6a330 2015-04-28 17:11:02.760 testtool[6243:203754] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[testtool.ViewController timeExpired]: unrecognized selector sent to instance 0x79f6a330' – Amit Raj Apr 28 '15 at 11:43
  • @Amit Raj - looks like you didn't add the timeExpired function to your code. – Istvan Apr 28 '15 at 11:52
  • I added that function – Amit Raj Apr 28 '15 at 14:48
  • In Objective-c, you can call timeExpired: (note : at the end) and add the parameter in the timeExpired:(NSTimer*) timer, but i don't know if in Swift apply the same thing. – Beto Apr 28 '15 at 16:50