下面是代碼 , 部分有注解
先創建一個類
#import <UIKit/UIKit.h> @interface MYjindutiao : UIView @property(strong,nonatomic)UIView *aview; @property(strong,nonatomic)UIView *bview; @property(strong,nonatomic)UILabel *laber; @property(strong,nonatomic)NSTimer *time; @property(assign,nonatomic)int a; @end
#import "MYjindutiao.h" @implementation MYjindutiao - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.aview=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 200, 30)]; self.aview.backgroundColor=[UIColor colorWithRed:0.082 green:0.969 blue:1.000 alpha:1.000]; //使它邊角變圓 self.aview.layer.cornerRadius=10; self.aview.layer.masksToBounds=YES; self.bview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 30)]; self.bview.backgroundColor=[UIColor colorWithRed:0.020 green:1.000 blue:0.085 alpha:1.000]; self.bview.layer.cornerRadius=10; self.bview.layer.masksToBounds=YES; self.laber=[[UILabel alloc]initWithFrame:CGRectMake(100, 200, 200, 200)]; self.laber.backgroundColor=[UIColor colorWithRed:1.000 green:0.885 blue:0.050 alpha:1.000]; //使laber變成球形 self.laber.layer.cornerRadius=100; self.laber.layer.masksToBounds=YES; //字體居中 self.laber.textAlignment=NSTextAlignmentCenter; //字體放大 self.laber.font=[UIFont systemFontOfSize:40 weight:40]; self.laber.textColor=[UIColor colorWithRed:0.957 green:0.950 blue:1.000 alpha:1.000]; [self addSubview:self.aview]; [self.aview addSubview:self.bview]; [self addSubview: self.laber]; self.time=[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(change) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.time forMode:NSDefaultRunLoopMode]; } return self; } -(void)change { CGRect chFrame=self.bview.frame; chFrame.size.width+=0.25; self.bview.frame=chFrame; self.laber.text=[NSString stringWithFormat:@"%.2f%%",self.bview.frame.size.width/2]; if (self.bview.frame.size.width==self.a) { //清除定時器 [self.time invalidate]; } } @end
#import <UIKit/UIKit.h> #import "MYjindutiao.h" @interface ViewController : UIViewController @property(strong,nonatomic)MYjindutiao *jindutiao; @end
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.jindutiao=[[MYjindutiao alloc]initWithFrame:CGRectMake(0, 100, 300, 500)]; self.jindutiao.a=160; [self.view addSubview:self.jindutiao]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end