ios - 为什么SnapKit的函数 `self`的闭包中没有 `makeConstraints`?
<p><pre><code>starLabel.snp.makeConstraints { make in
make.left.equalTo(starImageView.snp.right).offset(5)
make.centerY.equalToSuperview()
}
</code></pre>
<p><code>starImageView</code> 和 <code>starLabel</code> 是当前 ViewController 的属性。但是,为什么我可以忽略闭包中的 <code>self</code>(<code>self.starImageView</code>) 是 <code>makeConstraints</code> 中的参数?</p>
<p>而且在我的闭包中,我必须显式地写出<code>self</code>,否则编译器会报错:</p>
<blockquote>
<p>Reference to property 'starImageView' in closure requires explicit 'self.' to make capture semantics explicit</p>
<p>Insert 'self.'</p>
</blockquote>
<p> <a href="/image/jsGkS.jpg" rel="noreferrer noopener nofollow"><img src="/image/jsGkS.jpg" alt="enter image description here"/></a> </p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><pre><code>public func makeConstraints(_ closure: (_ make: ConstraintMaker) -> Void) {
ConstraintMaker.makeConstraints(item: self.view, closure: closure)
}
</code></pre>
<p>因为闭包不是<code>@escaping</code>,所以这意味着闭包只会在函数中运行。当函数越过闭包时就会被释放。
只有函数可以持有闭包。</p></p>
<p style="font-size: 20px;">关于ios - 为什么SnapKit的函数 `self`的闭包中没有 `makeConstraints`?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/52226961/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/52226961/
</a>
</p>
页:
[1]