1、oc中的写法,使用{ }来代表局部作用域
-(void)loadView {
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
{
UILabel *titleLabel = [[UILabel alloc]
initWithFrame:CGRectMake(150, 30, 200, 40)]; titleLabel.textColor = [UIColor redColor]; titleLabel.text = @"Title";
[view addSubview:titleLabel];
} {
}
self.view = view; }
2、swift中的写法
如果我们想类 似地使用局部 scope 来分隔代码的话,一个不错的选择是定义一个接受 ()->() 作为函数的全局 方法,然后执行它:
func local(_ closure: ()->()) { closure()
}
调用如下:
override func loadView() {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) view.backgroundColor = .white
local {
let titleLabel = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40)) titleLabel.textColor = .red
titleLabel.text = "Title"
view.addSubview(titleLabel)
}
local {
let textLabel = UILabel(frame: CGRect(x: 150, y: 80, width: 200, height: 40)) textLabel.textColor = .red
textLabel.text = "Text"
view.addSubview(textLabel)
}
self.view = view }
3、在 Objective-C 中还有一个很棒的技巧是使用 GNU C 的声明扩展来在限制局部作用域的时候同时 进行赋值,运用得当的话,可以使代码更加紧凑和整洁。
self.titleLabel = ({
UILabel *label = [[UILabel alloc]
initWithFrame:CGRectMake(150, 30, 20, 40)]; label.textColor = [UIColor redColor];
label.text = @"Title";
[view addSubview:label];
label; });
4、swift中只能使用匿名闭包来实现第3条中的写法
let titleLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40)) label.textColor = .red
label.text = "Title"
return label
}()
网友评论