ios - self.view.addSubview 和 view.addSubview 的区别

标签 ios swift addsubview

我已经用 swift 编写了一堆代码并且更喜欢以编程方式编写很多代码,我想知道这两者之间的区别是什么:

self.view.addSubview(someNewView)
view.addSubview(someNewView)

它们似乎都有效。出于某种原因更好吗?它们真的那么不同吗?

如果这是一个愚蠢的问题或已经回答,可以将其删除。只是一个想法。

最佳答案

没有真正的区别,尽管您可能会更频繁地看到以前的 Objective-C 开发人员使用 self。来自文档:

In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method.

...

The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

关于ios - self.view.addSubview 和 view.addSubview 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27752535/

相关文章:

ios - 在像 Twitter 这样的每个 View Controller 中使用不同颜色的导航栏(不使用 setbartintcolor)

iphone - 我想在同一 View Controller 中同时使用选项卡栏和导航栏

ios - Swift:重新加载关卡后不会调用 didBeginContact()

ios - 将另一个 Storyboard显示为 TabBarController 的第一个选项卡的内容

objective-c - 添加到 View 的 subview 的 UIButton 不会响应

ios - 发送到释放实例的消息

swift - 半透明 UINavigationBar 在 iOS 12 beta(GM 种子)上无法正常工作

ios - 是否必须使用autolayout才能使用stackview

ios - iMessage 扩展和 CoreData

ios - 如果将 UIButton 添加为 UIImageView 的 subview ,则单击它不起作用