IOS实现顶部显示信息

    做公司项目的时候有个需求,需要从顶端划出一个消息,显示一段时候后自动消失。

    实现如下:

    

    CGRect rect = [self.view bounds];
    CGFloat viewHeight = 50.0f;
    UIView *alertView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, -viewHeight, rect.size.width, viewHeight)];
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, rect.size.width, viewHeight, 8, 4 * rect.size.width, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);
    CGFloat colors[] =
    {
        255.0 / 255.0, 0.0 / 255.0, 0.0 / 255.0, 1.0,
        255.0 / 255.0, 0.0 / 255.0, 0.0 / 255.0, 1.0,
        255.0 / 255.0,  0.0 / 255.0, 0.0 / 255.0, 1.0,
    };//这里可以设置渐变色。
    CGGradientRef gradient = CGGradientCreateWithColorComponents
    (CGColorSpaceCreateDeviceRGB(), colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
    CGContextDrawLinearGradient(bitmapContext, gradient, CGPointMake(0.0f, 0.0f), CGPointMake(rect.size.width, rect.size.height), kCGGradientDrawsBeforeStartLocation);
    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
    UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    CGContextRelease(bitmapContext);
    
    [alertView setBackgroundColor:[UIColor colorWithPatternImage:uiImage]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 20.0f, rect.size.width, 24.0f)];
    [label setFont:[UIFont systemFontOfSize:20.0f]];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    label.textColor = [UIColor blackColor];
    label.text = @"网络出错!";
    [alertView addSubview:label];
    [self.view addSubview:alertView];
    //动画效果,从顶部出现,5秒后消失
    [UIView animateWithDuration:0.5f animations:^{
        [alertView setFrame:CGRectMake(0.0f, 0.0f, rect.size.width, viewHeight)];
    } completion:^(BOOL finished){
        if(finished){
            [UIView animateWithDuration:0.5f delay:5.0f options:UIViewAnimationOptionTransitionNone animations:^{
                [alertView setFrame:CGRectMake(0.0f, -viewHeight, rect.size.width, viewHeight)];
            } completion:^(BOOL finished){
                [alertView removeFromSuperview];
            }];
        }
    }];
View Code

    

posted @ 2014-01-15 16:26  暴Tyrant君  阅读(304)  评论(0编辑  收藏  举报