簡體   English   中英

Xamarin.Forms等效於layoutSubviews是什么?

[英]What is the Xamarin.Forms equivalent of layoutSubviews?

我正在將大型iOS代碼庫移植到Xamarin.Forms應用程序。 我們有很多自定義視圖,這些視圖通過在-layoutSubviews進行計算來執行其布局邏輯。 如果我需要根據堆棧或網格布局重新解釋這些計算,則代碼庫太大,無法及時移植。 我真正想要的是一個直接等效項,可以在其中將等效子視圖添加到我們的視圖中,而不必擔心它們的去向,然后是一個當視圖范圍更改時調用的方法,可以在其中設置子視圖的新邊界。 然后,我可以直接移植我們現有的iOS代碼。

Xamarin.Forms中是否有與-layoutSubviews等效的-layoutSubviews

我不確定layoutSubviews的表單是否等效,但是您正在談論的計算可以在稱為方法的內部完成:

protected override void OnSizeAllocated(double width, double height)
{
    base.OnSizeAllocated(width, height);
}

您需要從ContentPage或Any Page繼承以覆蓋此方法。

您可以通過繼承Xamarin.Forms.Layout類來創建自己的Layout。

public class CustomLayout : Layout<View>
{
    public CustomLayout ()
    {

    }
}

布局必須覆蓋LayoutChildren方法。 此方法負責將孩子放在屏幕上。

可以通過使用GetSizeRequest方法來測量子項,該方法將返回所需大小和子項所需的最小大小。

protected override void LayoutChildren (double x, double y, double width, double height)
{
    for (int i = 0; i < Children.Count; i++) {
        var child = (View) Children[i];
        // skip invisible children

        if(!child.IsVisible) 
            continue;
        var childSizeRequest = child.GetSizeRequest (double.PositiveInfinity, height);
        var childWidth = childSizeRequest.Request.Width;
        LayoutChildIntoBoundingRegion (child, new Rectangle (x, y, childWidth, height));
        x += childWidth;
    }
}

每當需要重新計算布局時,都會自動調用此方法。 如果布局由硬編碼或固定大小的元素組成,則將其大小硬編碼到此算法中,而不是進行測量。 GetSizeRequest調用是可以進行的一些最昂貴的調用,並且在運行時不可預測,因為子樹可能是任意復雜的。 如果不需要動態調整大小,則固定它們的大小是提高性能的一種好方法。

需要執行OnSizeRequest以確保在將新布局放入其他布局中時正確調整其大小。 在布局周期中,根據其上方的布局以及解析當前布局層次結構需要多少個布局例外,可能會多次調用此方法。

protected override SizeRequest OnSizeRequest (double widthConstraint, double heightConstraint)
{
    var height = 0;
    var minHeight = 0;
    var width = 0;
    var minWidth = 0;

    for (int i = 0; i < Children.Count; i++) {
        var child = (View) Children[i];
        // skip invisible children

        if(!child.IsVisible) 
            continue;
        var childSizeRequest = child.GetSizeRequest (double.PositiveInfinity, height);
        height = Math.Max (height, childSizeRequest.Minimum.Height);
        minHeight = Math.Max (minHeight, childSizeRequest.Minimum.Height);
        width += childSizeRequest.Request.Width;
        minWidth += childSizeRequest.Minimum.Width;
    }

    return new SizeRequest (new Size (width, height), new Size (minWidth, minHeight));
}

您可以在此處閱讀有關如何創建自定義布局的整個教程。

暫無
暫無

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

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