(ios實戰)實現類似於android 的toast控件


1實現原理

 創建一個自定義控件,控件中顯示文本,同時設置一個動畫,三秒鍾后,控件的alpha為0,動畫完成后,控件移出掉ViewControl

 

2 創建PopView

2.1 PopView.h 部分

@interface PopView : UIView
{
    UILabel         *_textLabel;
    int             _queueCount;
}

- (void) setText:(NSString *) text;

@end

2.2 PopView.m

#import "PopView.h"
#import <QuartzCore/QuartzCore.h>
@implementation PopView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0.75f];
        self.layer.cornerRadius = 5.0f;
        _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 10)];
        _textLabel.numberOfLines = 0;
        _textLabel.font = [UIFont systemFontOfSize:17];
        _textLabel.textColor = [UIColor whiteColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.backgroundColor = [UIColor clearColor];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_textLabel];
        _queueCount = 0;
    }
    return self;
}




- (void) setText:(NSString *) text
{
    _textLabel.frame = CGRectMake(0, 0, 100, 10);
    _queueCount ++;
    self.alpha = 1.0f;
    _textLabel.text = text;
    [_textLabel sizeToFit];
    CGRect frame = CGRectMake(5, 0, _textLabel.frame.size.width, _textLabel.frame.size.height);
    _textLabel.frame = frame;
   frame =  CGRectMake(self.frame.origin.x, self.frame.origin.y, _textLabel.frame.size.width+10, _textLabel.frame.size.height+10);
    self.frame = frame;
    [UIView animateWithDuration:3.0
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         self.alpha = 0;
                     }
                     completion:^(BOOL finished){
                         if (_queueCount == 1) {
                             [self removeFromSuperview];
                         }
                        _queueCount--;

                     }
     ];
    
}


@end

3 調用方式:

[self.view addSubview:_popView];
    [_popView setText:@"合成恢復"];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM