OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么SnapKit的函数 `self`的闭包中没有 `makeConstraints`? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:33
标题: ios - 为什么SnapKit的函数 `self`的闭包中没有 `makeConstraints`?

starLabel.snp.makeConstraints { make in
    make.left.equalTo(starImageView.snp.right).offset(5)
    make.centerY.equalToSuperview()
}

starImageViewstarLabel 是当前 View Controller 的属性。但是,为什么我可以忽略闭包中的 self(self.starImageView) 是 makeConstraints 中的参数?

而且在我的闭包中,我必须显式地写出self,否则编译器会报错:

Reference to property 'starImageView' in closure requires explicit 'self.' to make capture semantics explicit

Insert 'self.'

enter image description here



Best Answer-推荐答案


public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
        ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}

因为闭包不是@escaping,所以这意味着闭包只会在函数中运行。当函数越过闭包时就会被释放。 只有函数可以持有闭包。

关于ios - 为什么SnapKit的函数 `self`的闭包中没有 `makeConstraints`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52226961/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4