簡體   English   中英

如何以編程方式為其父視圖添加視圖大小?

[英]How to make a programmatically added view size to its parent view?

我正在使用具有自己的視圖的自定義鍵盤,該視圖在Interface Builder中進行編輯。

該視圖在加載時以編程方式添加到鍵盤根視圖。 它包含堆棧視圖,並會自動填充整個視圖。

問題是鍵盤視圖的大小與打開的應用程序的視圖不同。似乎它具有固定的大小,因為當我水平旋轉模擬器時,可以看到更多的寬度,而在垂直時看不到。

如何使其尺寸與放置的根視圖的寬度相同?

這是鍵盤在Interface Builder和運行iPhone 5S的模擬器中的外觀:

尺寸

首先,我們需要從布局更改中了解大小更改,我們可以這樣進行:

override var bounds: CGRect {
    didSet {
      print("Bounds have changed: \(bounds)")
    }
}

這應該在您的自定義鍵盤視圖中使用。 接下來,我們要更新自定義鍵盤布局。 查看您的屏幕快照,這表明我們需要做的就是調整鍵的高度和寬度,稍后您可以根據大小類的更改添加調整,從而更好地控制布局。 您將需要使用@IBOutlets或通過遍歷子視圖並手動查找和更改寬度和高度約束來保留對高度和寬度約束的引用,這兩者都是很繁瑣的,但是使用@IBOutlets更容易。

func updateKeys() {
    DispatchQueue.main.async {
        // Create array of width constraints
        let widthConstraints: [NSLayoutConstraint] = widthArray() 
        widthConstraints.forEach { _ in /* change width constant for current layout */ }

        // Create array of height constraints
        let heightConstraints: [NSLayoutConstraint] = heightArray() 
        heightConstraints.forEach { _ in /* change height constant for current layout */ }

    }
}

這只是一種方法,我發現對於自動布局,在復雜的布局中總會有一種方法,但是它應該向您展示可以使用的模式。

您是否嘗試實施這些通知?

[[NSNotificationCenter defaultCenter] addObserver:self
                                       selector:@selector(keyboardFrameWillChange:)
                                           name:UIKeyboardWillShowNotification
                                         object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
                                       selector:@selector(keyboardFrameWillChange:)
                                           name:UIKeyboardWillChangeFrameNotification
                                         object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                                           name:UIKeyboardWillHideNotification
                                         object:nil];

然后,在調用這些通知時,將視圖大小調整為鍵盤框架

CGRect keyboardFrame;
[[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];

CGRect viewFrame = keyboardFrame;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM