簡體   English   中英

限制超視圖內的視圖

[英]restrict a view inside the superview

我正在嘗試使用觸摸移動方法移動另一個 UIView - “B”(SuperView)內的 UIView - “A”(子視圖)。 我可以將 UIView 移動到超級視圖之外。 我想限制 Superview 邊界內的 UIView。 有什么辦法可以有一個通用的方法來測試子視圖是否在超級視圖的可見矩形內???

使用 clipsToBounds 方法或CGRectContainsRect

youSuperView.clipsToBounds = YES;

我認為它會對你有所幫助

聽起來您想限制子視圖 (viewA) 的移動,使其始終完全被父視圖 (viewB) 包含。 CGRectContainsRect 是正確的答案,但必須謹慎應用,因為子視圖框架是在其父視圖的坐標系中指定的。

// inside touches moved, compute the newViewAFrame based on the movement
// but only assign it if it meets the containment constraint:

if (CGRectContainsRect(viewB.bounds, newViewAFrame)) {
    viewA.frame = newViewAFrame;
}

請注意,我們沒有在檢查中提及 viewB.frame。 viewB 在其父級中的位置與 viewB 是否包含 viewA 無關。

我遇到了同樣的問題,這篇文章對我幫助很大,所以我將分享我的答案(這似乎完全符合您的需要):

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        if (SuperView.frame.contains(self.frame)) {
            let oldCenter = self.center
            self.center = touch.location(in: SuperView)
            if(!SuperView.frame.contains(self.frame)) {
                self.center = oldCenter
            }
        }
    }
}

非常簡單,您也可以在touchesMovedtouchesEnded方法中使用它,因此當您的 UIView 達到限制時它不會阻止您(這就是 oldCenter 存在的原因)。

正如@dahn 提到的,如果您的視圖在 SuperView 內部,則必須小心,因為第一個的坐標將限制在第二個的框架內,因此如果 SuperView 不是全屏視圖它可能會失敗

如果不是全屏視圖,則 SuperView 不能成為 SubView 的父親,因為它會導致錯誤。 解決方案是將 SuperView 和 SubView 都保留在第三個 View 中(因此它們的坐標系將相同並且可以正常工作)。

希望有一天能幫助某人:)

Swift 2.2: let rect1 = CGRect(...) let rect2 = CGRect(...)

有一種方法可以檢查這個 - CGRectContainsRect(rect1, rect2)

暫無
暫無

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

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