.addObservers 和 observevalue 方法如何在 iOS Swift 5 中工作

阿迪亞·瓦蓋拉

我正在為我的 Swift 項目使用 tableView.addObserver 和 observeValue 方法,以根據其內容提供 tableView 高度。它的工作完全正常,但我不知道如何。有人可以解釋我這是我的代碼。

 

    override func viewDidLoad() {
                super.viewDidLoad()
                self.tableView.addObserver(self, forKeyPath: "contentSize", options:         NSKeyValueObservingOptions.new, context: nil)
          }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
                tableView.layer.removeAllAnimations()
                heightTable.constant = tableView.contentSize.height
                UIView.animate(withDuration: 0.5) {
                    self.updateViewConstraints()
                }
            }
      
拉扎列夫祖博夫

我認為最好閱讀文檔。沒有人會比官方文檔更好地解釋你。鍵值觀察是一個眾所周知的,而不是新的和有據可查的概念。您可以從這個特定的方法文檔開始(易於搜索)。然後從那裡轉到一般主題

NSKeyValueObserving

An informal protocol that objects adopt to be notified of changes to the
specified properties of other objects.

Overview

You can observe any object properties including simple attributes, to-one
relationships, and to-many relationships. Observers of to-many relationships 
are informed of the type of change made — as well as which objects are 
involved in the change.

NSObject provides an implementation of the NSKeyValueObserving protocol that 
provides an automatic observing capability for all objects. You can further 
refine notifications by disabling automatic observer notifications and 
implementing manual notifications using the methods in this protocol.

所以它提到NSObject類已經實現了這種機制。所有UIViewController子類也是其後代,NSObject並免費提供相同的功能。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在我的iOS应用中检查Google身份验证状态(Swift 5)

如何在Swift 3、4和5中编写GCD中的dispatch_after?

如何在iOS Swift 3中以编程方式推送和呈现给UIViewController而不进行选择

如何在Swift(iOS)中创建单选按钮和复选框?

如何在swift5和Alamofire 5 Beta版本中获取和保存响应?

View Controller Containment如何在iOS 5中工作?

如何在Swift iOS 8中使用requestAccessToEntityType方法

如何在MapKit IOS8和Swift中在地图上设置边界

Swift如何在IOS中隐藏运营商,时间和电池

Web服务无法在Android Retrofit中工作,但可以在Postman和Swift / iOS中工作,未经授权就获得401

如何在iOS 11和Swift 4中从相机捕获深度数据?

如何在iOS Swift中实现评论和回复系统

如何在Swift 4和IOS 11中更改语音识别语言?

如何在Swift 5中获得安全区域的顶部和底部插图

如何在Apple Maps中更新路线-iOS 13.0中的Xcode Swift 5?

如何在表视图Swift 5中过滤和显示数据?

如何在Swift 5和iOS 13中使用CIFilter sunbeamsGenerator?

bitwise_and在Postgres 9.4和Hibernate 5中如何工作

如何在Swift iOS中通过Pincode获取城市,州和国家/地区名称?

Swift 3.0和iOS:如何在Swift中设置文件的删除权限

如何在 Swift iOS 中从字典中保存和检索对象数组值?

iOS Swift:如何隐藏和显示 UIViewController 中的按钮

如何在ios swift中的电话方法中处理completionHandler

如何在 swift 5(iOS) 中创建虚线步骤指示器

Swift:如何在 iOS 应用中隐藏 API URL 和参数

如何在 Swift iOS 中更改单选按钮选定的图像和相应的文本

如何在 Swift(iOS) 中结合平移和旋转变换动画?

如何在 ios swift 中為 VoiceOver 設置展開和折疊狀態?

KMM 和 iOS 中的傳遞依賴是如何工作的?