簡體   English   中英

你能將UIView剪輯子視圖限制在視圖的某些邊嗎?

[英]Can you limit UIView Clip Subviews to certain sides of a view?

我有一個UIScrollView,其中包含部分繪制在scrollview之外的其他子視圖。 這些視圖在滾動視圖上方垂直延伸。 是否可以僅允許在滾動視圖的頂部之外繪制子視圖,而不允許在滾動視圖的左側和右側之外繪制它們?

發生的事情是,當我手動向左和向右滾動時,由於內容大小,子視圖正在滾動視圖之外繪制。 一旦子視圖滾動到滾動視圖的框架之外,我想剪切子視圖。

有任何建議或可能嗎?

我已經設法通過使用layermask屬性和CALayer來實現此效果。 以下代碼段僅剪切視圖頂部和左側的視圖:

let maskLayer = CALayer()
maskLayer.backgroundColor = UIColor.blackColor().CGColor
maskLayer.frame = CGRectMake(0, 0, 2000, 2000) 

aView.layer.mask = maskLayer

請注意,我使用任意數字2000作為剪切的最右邊界和下邊界,因此您需要根據您希望其他視圖剪輯的距離來調整數量。

你不能指定你想要剪輯的單個邊,但你基本上可以通過在你想要剪輯的邊緣旁放置一個新的UIView (並因此有效地剪裁它)來偽造它。 或者,您可以考慮更改視圖層次結構的方法,以便您根本不必剪切子視圖(可能通過以某種方式調整滾動視圖的邊界和布局)。

以下是我在Objective-C中實現Max Chuquimia的優秀解決方案的方法:

CALayer* maskLayer = [CALayer layer];
maskLayer.backgroundColor = [UIColor blackColor].CGColor;
maskLayer.frame = CGRectMake(0,-100,
                            parentView.frame.size.width, parentView.frame.size.height + 100);
parentView.layer.mask = maskLayer;

父視圖的任何部分或其子視圖都不會被蒙版中的黑色像素覆蓋。

在此片段中,我們向左和向右剪輯,但在父視圖的頂部和下方留下100個點以使子項溢出。 (掩碼大於父視圖)

將剪輯限制在視圖的某些邊:

例如,在表或集合視圖上執行此操作是很常見的:

/*
This is a UICollectionView, which clips normally on the left and right,
but allows some extra space horizontally.
A typical example is you need to clip the scrolling items but you
still need to allow shadows.
*/

import Foundation
import UIKit

class CustomClipCollectionView: UICollectionView {

    private lazy var extraSpaceOnBaseButStillClipSidesNormally: CALayer = {
        let l = CALayer()
        l.backgroundColor = UIColor.black.cgColor
        return l
    }()

    override func layoutSubviews() {
        extraSpaceOnBaseButStillClipSidesNormally.frame = bounds.insetBy(
                          dx: 0, dy: -10)
        layer.mask = extraSpaceOnBaseButStillClipSidesNormally
        super.layoutSubviews()
    }
}

注意! 使用此功能時,您關閉了正常的“剪輯到邊界”功能。 用於裁剪的“.mask”系統是不同的,並且與“剪輯到界限”系統是分開的。

暫無
暫無

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

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