聲明之前加上static,就是靜態變量。全局變量和靜態全局變量都是靜態存儲的;在存儲上無區別。區別在於他們的作用域;全局變量的作用域是整個源程序,當源程序有多個源文件組成時,全局變量在各個源程序文件都是有效的;而靜態全局變量怎被限制了作用域,只在定義該變量的源文件內有用在同一程序的其他源文件不能使用! 還有靜態全局變量只初始化一次,防止在其他源文件調用!而全局變量可以在其他源文件初始化!!
demo呈現:
在一個for循環中實現動態排版效果:
- (void)viewDidLoad
{
[super viewDidLoad];
static int _height = 0;
for (int j = 0; j<5; j++) {
UILabel *lab = [[UILabel alloc]init];
lab.textAlignment = UITextAlignmentLeft;
lab.lineBreakMode = UILineBreakModeWordWrap;
lab.numberOfLines = 0;
lab.font = [UIFont systemFontOfSize:13.0f];
lab.backgroundColor = [UIColor clearColor];
NSString * _connet = [NSString stringWithFormat:@"我的祖國我的祖國我的祖國我的祖國我的祖國我的祖國我的祖國我的祖國"];//_connet的內容可以是動態內容
[lab setText:_connet];
CGSize constraint = CGSizeMake(100, 2000);//label內容設置大小
CGSize size = [_connet sizeWithFont:[UIFont systemFontOfSize:13.0f]constrainedToSize:constraint1 lineBreakMode:UILineBreakModeWordWrap];
lab.frame = CGRectMake(100, _height+50, 100, size.height);
_height = lab.frame.origin.y+lab.frame.size.height-50;//需要減去50,避免重複增加
[self.view addSubview:lab];
[lab release];
}
}
這是我在項目中遇到的一個知識點,分享給大家。