[英]How to get the tab bar height in a Xamarin.Forms page
我在我的內容頁面中顯示一個圖像,使其高度是頁面高度的固定百分比。 我這樣做是使用星形單位行高的網格。 但是,當內容頁面放置在TabbedPage中時,總網格高度似乎是[屏幕減去標簽欄高度],因此圖像看起來有點短。
如果我可以訪問內容頁面中的標簽欄高度,則可以對百分比進行簡單調整。
題:
1)如何在內容頁面中獲得標簽欄高度?
2)有沒有更好的方法來達到預期的效果?
1)如何在內容頁面中獲得標簽欄高度?
我們無法直接從PCL獲取tabbar高度。只需要TabbedRenderer
的自定義渲染器
[assembly: ExportRenderer(typeof(TabbedPage),
typeof(CustomTabbedPageRenderer))]
namespace TabbedPageWithNavigationPage.iOS
{
class CustomTabbedPageRenderer : TabbedRenderer
{
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
App.TabHeight = (int)TabBar.Frame.Height;
}
}
}
在PCL中定義App
中的TabHeight
public static int TabHeight { get; set; }
在TabbedPage
獲取高度
protected override void OnAppearing()
{
base.OnAppearing();
int height = App.TabHeight;
}
2)有沒有更好的方法來達到預期的效果?
我們最好不要在Image上設置固定幀,也不應該手動操作幀。
Image
Aspect
可以幫助我們按照自己的意願顯示圖像。
編輯:
我建議你獲取屏幕大小並根據屏幕大小計算百分比並使用變量值而不是比例值,這樣,你可以使用除AbsoluteLayout之外的其他布局,但我使用AbsoluteLayout作為我的例子:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}
***在我的測試中,當我使用AbsoluteLayout比例法時
AbsoluteLayout.LayoutBounds = "0,0,1,0.25" AbsoluteLayout.LayoutFlags="All"
兩個圖像大小的結果將略有不同如果頁面使用有或沒有
Tabbedpage
所以我建議使用后面的代碼來獲取基於[屏幕高度*百分比]的圖像大小。
TabbedPage
XAML:
<?xml version="1.0" encoding="utf-8"?>
<TabbedPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:AbsoluteLayoutExample" x:Class="AbsoluteLayoutExample.AbsoluteLayoutExamplePage">
<ContentPage x:Name="MyPage" Title = "Page 1">
<AbsoluteLayout>
<Image x:Name="image" Source="icon.png" Aspect="AspectFill" />
</AbsoluteLayout>
</ContentPage>
<ContentPage Title = "Page 2">
<Label Text="Hello" />
</ContentPage>
</TabbedPage>
代碼隱藏:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0,0,imageWidth,imageHeight));
AbsoluteLayout.SetLayoutFlags(image,AbsoluteLayoutFlags.None);
}
僅限內容頁面:
XAML:
<?xml version="1.0" encoding="utf-8"?>
<ContentPage Padding="0,20,0,0"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:ContentPageWidthAndHieght"
x:Class="ContentPageWidthAndHieght.ContentPageWidthAndHieghtPage">
<AbsoluteLayout>
<Image x:Name="image" Source="icon.png" Aspect="AspectFill"/>
</AbsoluteLayout>
</ContentPage>
代碼隱藏:
protected override void OnAppearing()
{
var imageWidth = this.Width;
var imageHeight = this.Height * 0.25;
AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, imageWidth, imageHeight));
AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.