.NET MAUI Shell TabBar does not behave as expected - ios

In our .Net MAUI iOS app, we use Shell TabBar:
<TabBar>
<Tab Title="Home" Icon="{StaticResource IconHome}">
<ShellContent ContentTemplate="{DataTemplate local:MainPage}" />
</Tab>
<Tab Title="Coverage
Calculator" Icon="{StaticResource IconCalculator}" >
<ShellContent ContentTemplate="{DataTemplate calculator:CoverageCalculatorPage}" />
</Tab>
<Tab Title="Distributor
Locator" Icon="{StaticResource IconLocator}">
<ShellContent ContentTemplate="{DataTemplate locator:DistributorsLocatorPage}" />
</Tab>
<Tab Title="Scan
QR Code" Icon="{StaticResource IconQrScanner}">
<ShellContent ContentTemplate="{DataTemplate qrScanner:QrScannerPage}" />
</Tab>
<Tab Title="More" Icon="{StaticResource IconMore}">
<ShellContent ContentTemplate="{DataTemplate more:MoreFeaturesPage}" />
</Tab>
</TabBar>
As you can see, some tab titles have two lines. To show both lines, and to center the titles' texts, I use custom renderer:
internal class MyShellRenderer : ShellRenderer
{
protected override IShellTabBarAppearanceTracker CreateTabBarAppearanceTracker()
{
return new MyCreateTabBarAppearanceTracker();
}
public class MyCreateTabBarAppearanceTracker : ShellTabBarAppearanceTracker, IShellTabBarAppearanceTracker
{
void IShellTabBarAppearanceTracker.SetAppearance(UITabBarController controller, ShellAppearance appearance)
{
base.SetAppearance(controller, appearance);
var items = controller.TabBar.Items;
if (items == null)
{
return;
}
for (int i = 0; i < items.Length; i++)
{
if (items[i] == null) continue;
else
{
UITabBarItem item_temp = items[i];
UIView view = item_temp.ValueForKey(new Foundation.NSString("view")) as UIView;
UILabel label = view.Subviews[1] as UILabel;
label.Lines = 2;
label.LineBreakMode = UILineBreakMode.WordWrap;
label.TextAlignment = UITextAlignment.Center;
}
}
}
}
}
With this custom renderer, the goal is achieved only partially. Here is how the TabBar looks at the beginning:
The titles are centered, but only the first line shows up.
If the app is placed in the background, when it re-appears, all tabs have now two lines, but the text is not centered:
If I touch a tab, the texts get centered:
But the text of the second tab is truncated.
And the 2nd line of the fourth tab that has two words, loses the second word (wrapped to the 3rd line).
And when the phone is turned to landscape view, the labels are distorted even more:
Only one line shows up, but wrapped to occupy both lines.
How can this behavior be fixed? I.e. 1) how to make the text to show both centered lines initially, and 2) how to increase the tabs' width to avoid truncating, and 3) how to fix the landscape view?

Related

.NET MAUI: Unwanted whitespace at bottom of screen using grid layout

I have a simple grid layout:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Button Grid.Row="0"
Text="Test1"
VerticalOptions="Fill"
BackgroundColor="Green"/>
<Button Grid.Row="1"
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>
</Grid>
I expect the red area to extend all the way to the bottom of the screen. However, There's some white space.
If I change it to a collection view with a footer, it properly fills the bottom section of the screen:
For reference:
<CollectionView>
<CollectionView.Header>
<Button
Text="Test1"
VerticalOptions="Fill"
BackgroundColor="Green"/>
</CollectionView.Header>
<CollectionView.EmptyView>
<Label Text="No items"/>
</CollectionView.EmptyView>
<CollectionView.Footer>
<Button
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>
</CollectionView.Footer>
</CollectionView>
Is there a correct way to fill that bottom "footer" area on a grid view? or without using a collection view?
I don't think it matters but I'm running in iOS simulator on Mac iOS 16.2.
The white space at the bottom of the screen is iOS Page UseSafeArea in iOS. However, it is not yet implemented in Maui and you can track the MAUI issue here: https://github.com/dotnet/maui/issues/5856.
As an alternative workaround for now, you can set the Page Padding value to remove the bottom white space. In the OnAppearing Method, set the safeInsets of the page:
protected override void OnAppearing()
{
base.OnAppearing();
DeviceSafeInsetsService d = new DeviceSafeInsetsService();
double topArea = d.GetSafeAreaTop();
double bottomArea = d.GetSafeAreaBottom();
var safeInsets = On<iOS>().SafeAreaInsets();
safeInsets.Top = -topArea;
safeInsets.Bottom = -bottomArea;
Padding = safeInsets;
}
And then write platform specific code to get the topArea and bottomArea value.
1.Create DeviceSafeInsetsService.cs in Project folder.
public partial class DeviceSafeInsetsService
{
public partial double GetSafeAreaTop();
public partial double GetSafeAreaBottom();
}
2.And then under the Project/Platform/iOS folder, create a iOS specific class DeviceSafeInsetsService.cs:
public partial class DeviceSafeInsetsService
{
public partial double GetSafeAreaBottom()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
var bottomPadding = window.SafeAreaInsets.Bottom;
return bottomPadding;
}
return 0;
}
public partial double GetSafeAreaTop()
{
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
UIWindow window = UIApplication.SharedApplication.Delegate.GetWindow();
var TopPadding = window.SafeAreaInsets.Top;
return TopPadding;
}
return 0;
}
}
For more details, you can refer to this sample .NET MAUI Platform Code Sample.
Set your Corner Radius property to 0 in your button control's property definition
<Button
CornerRadius="0"
Text="Test2"
VerticalOptions="Fill"
BackgroundColor="Red"/>

Matching the vertical scroll position of a Grid to a RichEditBox or TextBox

I've got a Windows Store app with a RichEditBox (editor) and a Grid (MarginNotes).
I need the vertical scroll position of the two elements to be matched at all times. The purpose of this is to allow the user to add notes in the margin of the document.
I've already figured out Note positioning based on the cursor position - when a note is added, a text selection is made of everything up to the cursor. that selection is then added to a second, invisible RichEditBox, inside a StackPanel. I then get the ActualHeight of this control which gives me the position of the note in the grid.
My issue is that when I scroll the RichEditBox up and down, the Grid does not scroll accordingly.
First Technique
I tried putting them both inside a ScrollViewer, and disabling scrolling on the RichEditBox
<ScrollViewer x:Name="EditorScroller"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="{Binding *" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Grid x:Name="MarginNotes" Grid.Column="0" HorizontalAlignment="Right"
Height="{Binding ActualHeight, ElementName=editor}">
</Grid>
<StackPanel Grid.Column="1">
<RichEditBox x:Name="margin_helper" Opacity="0" Height="Auto"></RichEditBox>
</StackPanel>
<RichEditBox x:Name="editor" Grid.Column="1" Height="Auto"
ScrollViewer.VerticalScrollBarVisibility="Hidden" />
</Grid>
</ScrollViewer>
When I scroll to the bottom of the RichEditBox control, and hit enter a few times, the cursor drops out of sight. The ScrollViewer doesn't scroll automatically with the cursor.
I tried adding C# code which would check the position of the cursor, compare it to the VerticalOffset and height of the editor, and then adjust the scroll accordingly. This worked, but was incredibly slow. Initially I had it on the KeyUp event which brought the app to a standstill when I typed a sentence. Afterwards I put it on a 5 second timer, but this still slowed down the app performance and also meant that there could be a 5 second delay between the cursor dropping out of sight and the RichEditBox scrolling.
Second Technique
I also tried putting just MarginNotes in its own ScrollViewer, and programmatically setting the VerticalOffset based off my RichEditBoxs ViewChanged event.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="{Binding *" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<ScrollViewer x:Name="MarginScroller" Grid.Column="0"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid x:Name="MarginNotes" HorizontalAlignment="Right"
Height="{Binding ActualHeight, ElementName=editor}">
</Grid>
</ScrollViewer>
<StackPanel Grid.Column="1">
<RichEditBox x:Name="margin_helper" Opacity="0" Height="Auto"></RichEditBox>
</StackPanel>
<RichEditBox x:Name="editor" Grid.Column="1" Height="Auto"
Loaded="editor_loaded" SizeChanged="editor_SizeChanged" />
</Grid>
relevant event handlers
void editor_Loaded(object sender, RoutedEventArgs e)
{
// setting this in the OnNavigatedTo causes a crash, has to be set here.
// this uses WinRTXAMLToolkit as suggested by Nate Diamond to find the
// ScrollViewer and add the event handler
editor.GetFirstDescendantOfType<ScrollViewer>().ViewChanged += editor_ViewChanged;
}
private void editor_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
{
// when the RichEditBox scrolls, scroll the MarginScroller the same amount
double editor_vertical_offset = ((ScrollViewer)sender).VerticalOffset;
MarginScroller.ChangeView(0, editor_vertical_offset, 1);
}
private void editor_SizeChanged(object sender, SizeChangedEventArgs e)
{
// when the RichEditBox size changes, change the size of MarginNotes to match
string text = "";
editor.Document.GetText(TextGetOptions.None, out text);
margin_helper.Document.SetText(TextSetOptions.None, text);
MarginNotes.Height = margin_helper.ActualHeight;
}
This worked, but was quite laggy as scrolling is not applied until the ViewChanged event fires, after scrolling has stopped. I tried using the ViewChanging event, but it does not fire at all for some reason. Additionally, the Grid was sometimes mis-positioned after a fast scroll.
So, what makes this difficult is that the size of the text or the placement of the text in different types of TextBoxes means that syncing the scrollbar doesn't guarantee you are syncing the text. Having said that, here's how you do it.
void MainPage_Loaded(object sender, RoutedEventArgs args)
{
MyRichEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, MyTextBox.Text);
var textboxScroll = Children(MyTextBox).First(x => x is ScrollViewer) as ScrollViewer;
textboxScroll.ViewChanged += (s, e) => Sync(MyTextBox, MyRichEditBox);
}
public void Sync(TextBox textbox, RichEditBox richbox)
{
var textboxScroll = Children(textbox).First(x => x is ScrollViewer) as ScrollViewer;
var richboxScroll = Children(richbox).First(x => x is ScrollViewer) as ScrollViewer;
richboxScroll.ChangeView(null, textboxScroll.VerticalOffset, null);
}
public static IEnumerable<FrameworkElement> Children(FrameworkElement element)
{
Func<DependencyObject, List<FrameworkElement>> recurseChildren = null;
recurseChildren = (parent) =>
{
var list = new List<FrameworkElement>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is FrameworkElement)
list.Add(child as FrameworkElement);
list.AddRange(recurseChildren(child));
}
return list;
};
var children = recurseChildren(element);
return children;
}
Deciding when to invoke the sync is tricky. Maybe on PointerReleased, PointerExit, LostFocus, KeyUp - there are a lot of ways to scroll is the real issue there. You might need to handle all of those. But, it is what it is. At least you can.
Best of luck.

Android align button and text in a table layout

I am trying to create a table view with a text view and a button in android. Below is my sample code ( work in progress ). As I am very new to android please help me how to arrange the text view and the button as in the image. Now I am getting button and text view. But its weird.
My Code
TableLayout table = (TableLayout)findViewById(R.id.tableLayout_1);
for (int i = 0; i<30; i++)
{
TableRow row = new TableRow(this);
row.setBackgroundColor(Color.DKGRAY);
TextView tv = new TextView(this);
Button btn=new Button(this);
tv.setTextAppearance(getApplicationContext(), R.style.maxWid);
tv.setText("Sample Text Here");
row.addView(tv);
btn.setText("Approves");
row.addView(btn);
table.addView(row);
}
Style.xml
<style name="maxWid">
<item name="android:textStyle">bold|italic</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:layout_width">fill_parent</item>
</style>
main_layout.xml
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"
android:layout_weight="1">
<TableLayout
android:id="#+id/tableLayout_1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
>
</TableLayout>
</ScrollView>
Expected format
Fighting with this since 1 day.. Please help
Thanks in advance!
what you can do here is create a layout xml using RelativeLayout and then add that into your TableRow.

Moving a toolbar button in XUL

I'm trying to get an element to move from right to left in XUL. I am doing this with a toolbar and want one toolbarbutton w/ a label to remain anchored to the right, while one of them moves from right to left, starting to the left of the anchor.
I'm trying to achieve this effect by modifying marginLeft, but my element stays still. I'm not really sure why it does not move.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE overlay >
<overlay id="my-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script type="application/x-javascript">
// Install load handler
var marginLeft = 0;
window.addEventListener("load", function(e) {
function moveIt() {
document.getElementById("moveit").style.marginLeft = marginLeft + "px";
marginLeft -= 30;
}
setInterval(moveIt, 1000);
}, false);
</script>
<vbox id="browser-bottombox">
<toolbar id="theToolbar">
<!-- holds the scrolling items and the refresh time -->
<hbox id="scrollingItemContainer" flex="1" align="end">
<!-- container for our scrolling items -->
<spacer flex="1"/>
<hbox id="movingItems" align="end">
<toolbarbutton id="moveit" label="moving"/>
</hbox>
<hbox>
<toolbarbutton id="rightAnchor" label="right"/>
</hbox>
</hbox>
</toolbar>
</vbox>
</overlay>
Any help you can provide will be helpful. I've tried this on FF4, but I think the problem exists on FF3 as well.
I should note that if I add a spacer with flex=1 after scrollingItemContainer then I see the item move, but it is not anchored to the right.

Default Layout Orientation when printing XPSs using the WPF XPS Viewer

Is there a way to set the Default Layout Orientation when printing XPSs using the WPF XPS Viewer?
My fixed document XPS has its page orientation set to Landscape, the Page Media Size has a width that is longer that its height and it displays correctly in the Viewer as Landscape.
Its just that when you hit the print button the Print Dialog preferences are defaulted to Portrait and it prints as such.
I'd rather not have to alter the users default print settings I'd much prefer it if the XPS Viewer would print the XPS as it was designed to be printed.
Fill the field of the PrintTicket:
PrintDialog pd = new PrintDialog();
PrintTicket pt = new PrintTicket();
pt.PageOrientation = PageOrientation.Landscape;
pd.PrintTicket = pd.PrintQueue.MergeAndValidatePrintTicket(pd.PrintQueue.DefaultPrintTicket, pt).ValidatedPrintTicket;
if (pd.ShowDialog() == true)
{
...
}
I believe the correct way to do this when creating a FixedDocument, is set the RenderTransform = RotateTransform(90) on the page content when the dimensions are higher than they are wide.
Example:
var visualContent = new Image
{
Source = image,
Stretch = Stretch.Uniform
};
visualContent.RenderTransformOrigin = new Point(0.5, 0.5);
visualContent.RenderTransform = new RotateTransform(90);
FixedPage fixedPage = new FixedPage();
fixedPage.Children.Add(visualContent);
var pageContent = new PageContent
{
Child = fixedPage
};
Not sure if that helps with a pre-existing XPS document however.
This is not really a problem with MXDW but one with the way drivers work on Windows. The user choice(s) is/are saved for a particular session. This means that you can reuse firs-print settings when printing between the first print and quitting the application. Most printers behave this way, until unless one comes up with a way to save this information somewhere and let the user re-use it across sessions.
So, I tried hacking the GPD file (where printing information for a printer is typically stored). The orientation has two possible values: PORTRAIT and LANDSCAPE_CC270 with the default being set to PORTRAIT. See below:
*%******************************************************************************
*% Orientation
*%******************************************************************************
*Feature: Orientation
{
*rcNameID: =ORIENTATION_DISPLAY
*DefaultOption: PORTRAIT
*Option: PORTRAIT
{
*rcNameID: =PORTRAIT_DISPLAY
}
*Option: LANDSCAPE_CC270
{
*rcNameID: =LANDSCAPE_DISPLAY
}
}
Now, if I were to change swap the default value to LANDSCAPE_CC270, the printing preferences stop coming up (and any print would fail). In fact, it appears, that specifying any other value keeps the default to PORTRAIT. Definitely, MS is
doing some sort of check to prevent us from hacking this driver. Looks like MS doesn't
want anyone to tamper with its settings :(
But you could try flirting with the GPD values a bit more and see if something of your liking comes up. Will keep hacking a bit more.
Caveat: GPD files shouldn't be tampered with if you don't know what you are doing. If you
still want to go ahead make a backup!
Hint: They are stored in %WINDOWS%system32\spool\drivers\w32x86\3 folder.
<Grid Margin="0,0,-8,-8">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<FlowDocumentScrollViewer Name="printpanel" HorizontalAlignment="Left" Width="959" FontFamily="Arial" Margin="0,-10,0,10">
<FlowDocument x:Name="FD">
<BlockUIContainer>
<Canvas>
<Label x:Name="lblReceipt" Visibility="Visible" Content="Receipt No." HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Top="178" FontSize="12" Canvas.Left="60"/>
<Label x:Name="txtReceiptNo" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="200" FontSize="12" Canvas.Left="187" Canvas.Top="177" FontFamily="Arial"/>
<Label x:Name="lblmemNo" Visibility="Visible" Content="Membership No." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="12" Canvas.Left="462" Canvas.Top="177"/>
<Label x:Name="txtMembershipNo" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="177" FontSize="12" Canvas.Left="604" Canvas.Top="177" FontFamily="Arial">
</Label>
<Label x:Name="lblAuthCentr" Visibility="Visible" Content="Authorised Center." HorizontalAlignment="Left" VerticalAlignment="Top" Canvas.Left="60" Canvas.Top="221" FontSize="12"/>
<TextBox x:Name="txtAuthCentr" HorizontalAlignment="Left" TextWrapping="WrapWithOverflow" Padding="10,3,3,0" Height="38" VerticalAlignment="Top" Width="219" FontSize="12" Canvas.Left="238" Canvas.Top="219" FontFamily="Arial"/>
<Label x:Name="lblSector" Visibility="Visible" Content="Sector." HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="12" Canvas.Left="492" Canvas.Top="220"/>
<Label x:Name="txtSector" BorderThickness="2" BorderBrush="Black" HorizontalAlignment="Left" Padding="10,3,3,0" Height="23" VerticalAlignment="Top" Width="115" FontSize="12" Canvas.Left="567" Canvas.Top="220" FontFamily="Arial"/>
</Canvas>
</BlockUIContainer>
</FlowDocument>
</FlowDocumentScrollViewer>
<Button Name="btnOk" Content="Print" Height="30" Grid.Row="1" Click="btnOk_Click" Margin="355,0,404,0"></Button>
</Grid>
Just set FlowDocument Height and width
set FD.PageWidth = 1100; FD.PageHeight = 600;
private void btnOk_Click(object sender, RoutedEventArgs e)
{
if (File.Exists("printPreview.xps"))
{
File.Delete("printPreview.xps");
}
var xpsDocument = new XpsDocument("printPreview.xps", FileAccess.ReadWrite);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
DocumentPaginator docPage;
FD.PageWidth = 1100; // set FlowDocument Width
FD.PageHeight = 600; // set FlowDocument Height
docPage = ((IDocumentPaginatorSource)FD).DocumentPaginator;
writer.Write(docPage);
Document = xpsDocument.GetFixedDocumentSequence();
this.Close();
xpsDocument.Close();
var windows = new PrintWindow(Document);
windows.ShowDialog();
}

Resources