I'm trying to build a Chat app UI, the idea of the Layout was pretty simple:
When the input bar is focused, keyboard show up and "push" up the chat bar, as it's a grid, the ListView will resize to fit the screen:
I update the input bar's margin to "push" it up:
NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
CGSize keyboardSize = result.RectangleFValue.Size;
if (Element != null){
Element.Margin = new Thickness(0, 0, 0,keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated
}
And this is the result:
https://drive.google.com/file/d/1S9yQ6ks15BRH3hH0j_M8awpDJFRFitUi/view?usp=sharing
The view did push up and the ListView also resized as expected, however there are two issues that I had no idea how to solve it:
How can I retain the ListView scroll position after resize?
Lack of animation to push up the view
I have search over the web, tried IQKeyboardManager and KeyboardOverLap, The push up animation is nice and smooth, however strange things happened:
https://drive.google.com/file/d/1Zm0lMKB3wq07ve67wlcvLuNM_6Waad7R/view?usp=sharing
Instead of resizing the ListView, this approach Push the entire ListView up, that I cannot see the first few items, of course the scroll bar can be scroll out of screen
Extra strange spaces at the bottom of the ListView
Any help will be appreciated, thank you!
Solution:
void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
{
NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
CGSize keyboardSize = result.RectangleFValue.Size;
if (Control != null)
{
int bottomMargin = 0;
var sa = UIApplication.SharedApplication.KeyWindow.SafeAreaInsets;
bottomMargin = (int)sa.Bottom;
CGPoint offset = Control.ContentOffset;
var difference = keyboardSize.Height - bottomMargin;
if (Control.ContentSize.Height > Control.Frame.Height)
{
offset.Y += difference;
Control.SetContentOffset(offset, true);
}
else if (Control.ContentSize.Height + keyboardSize.Height > Control.Frame.Height)
{
offset.Y += Control.ContentSize.Height + keyboardSize.Height - Control.Frame.Height - bottomMargin;
Control.SetContentOffset(offset, true);
}
Control.ContentInset = new UIEdgeInsets(0, 0, difference, 0);
Control.ScrollIndicatorInsets = Control.ContentInset;
}
}
void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
{
if (Control != null)
{
Control.ContentInset = new UIEdgeInsets(0, 0, 0, 0);
Control.ScrollIndicatorInsets = new UIEdgeInsets(0, 0, 0, 0);
}
}
Solution:
Refer the following code
in iOS Custom Renderer
protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
{
base.OnElementChanged(e);
if(Control!=null)
{
Control.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag;
NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("KeyBoardWillShow:"), new NSString("UIKeyboardWillShowNotification"), null);
NSNotificationCenter.DefaultCenter.AddObserver(this, new Selector("KeyBoardWillHide:"), new NSString("UIKeyboardWillHideNotification"), null);
}
}
[Export("KeyBoardWillShow:")]
void KeyBoardWillShow(NSNotification note)
{
NSValue keyboardRect = (NSValue)note.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
Control.ContentInset = new UIEdgeInsets(0,0, keyboardRect.RectangleFValue.Size.Height,0);
}
[Export("KeyBoardWillHide:")]
void KeyBoardWillHide(NSNotification note)
{
Control.ContentInset = UIEdgeInsets.Zero;
}
Related
When I focus that Editor, a keyboard overlaps Editor and Button. I know, there is a solution: putting elements inside ScrollView, but this solution makes huge problems with scrolling ListView inside ScrollView. What should I do, to make it work properly?
Layout:
red - ScrollView,
green - ListView,
blue - StackLayout with Editor and Button.
Here is the video how this works:
https://streamable.com/wvd3h
Solution #2 is to use Xamarin.Forms.Plugins - KeyboardOverlap, but this plugin has a problem with tab bar on TabbedPage
Rather than using a scrollview, you could create a custom iOS renderer that shifts your view up (using the margin) when the keyboard is active.
An example of this can be seen here:
https://github.com/rdelrosario/ChatUIXForms/blob/master/ChatUIXForms.iOS/Renderers/ChatEntryRenderer.cs
Relevant code:
void RegisterForKeyboardNotifications()
{
if (_keyboardShowObserver == null)
_keyboardShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow);
if (_keyboardHideObserver == null)
_keyboardHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide);
}
void OnKeyboardShow(object sender, UIKeyboardEventArgs args)
{
NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey));
CGSize keyboardSize = result.RectangleFValue.Size;
if (Element != null)
{
Element.Margin = new Thickness(0, 0, 0, keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated
}
}
void OnKeyboardHide(object sender, UIKeyboardEventArgs args)
{
if (Element != null)
{
Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed
}
}
void UnregisterForKeyboardNotifications()
{
if (_keyboardShowObserver != null)
{
_keyboardShowObserver.Dispose();
_keyboardShowObserver = null;
}
if (_keyboardHideObserver != null)
{
_keyboardHideObserver.Dispose();
_keyboardHideObserver = null;
}
}
On Android, it's likely not an issue, but if it is, you could try
android:Application.WindowSoftInputModeAdjust="Resize"
I'm using a UITabbarViewController in a relatively simple way. My issue only appears on iPad devices of iOS11 version. It's not visible on iOS10 or iPhone.
If you look at the screenshot, you can see that the background color of the tab is not aligned. Actually, it is aligned, it's the tabbar itself that is not taking the full width. So the background color is overlapping towards the central button because it's not using the space on the far left and far right.
I'm assuming that the tabbar is broken (and not my background colors, which are drawn manually) because the edges of the outsides tabs are not clickable, and yet the item positioning is set to be filling the width of the screen :
TabBar.ItemPositioning = UITabBarItemPositioning.Fill;
The items sizes are wrong if you consider the tabbar fullscreen, but they are if you consider the "reduced" version. So i'm pretty sure it's all good there, as long as the tabbar decides to take the full width of the screen, the buttons and background color will then have the correct measurements.
I've tried using View.LayoutIfNeeded() and SetNeedsLayout() to force a redraw, but to no avail.
I'm not sure why it's even behaving like so, and since it's the default behaviour of the OS and I haven't done anything particular, I'm not certain of what can even be tried.
Here's some relevant code :
MainTabbarController tabController = (MainTabbarController)Window.RootViewController;
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
ConfigureTabbar();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
UIViewController[] tabs = //Create the VCs in the most basic way
SetViewControllers(tabs, false);
}
protected virtual void ConfigureTabbar()
{
TabBar.Translucent = false;
TabBar.ItemPositioning = UITabBarItemPositioning.Fill;
TabBar.ItemSpacing = 0;
//View.LayoutIfNeeded();
float tabbarItemWidth = (float)Math.Ceiling(View.Bounds.Width / TabBar.Items.Length) + 1; //+ 1 to avoid the right pixel that was not filled on the right tab. Strange behaviour...
TabBar.ItemWidth = tabbarItemWidth;
//var version = NSProcessInfo.ProcessInfo.OperatingSystemVersion;
NSOperatingSystemVersion ios11 = new NSOperatingSystemVersion(11, 0, 0);
if (NSProcessInfo.ProcessInfo.IsOperatingSystemAtLeastVersion(ios11))
{
if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
{
TabBar.SelectionIndicatorImage = _viewModel.Styles.Colors.ActiveTabColor.ToNative().ToImage(new CGRect(0, -View.SafeAreaInsets.Bottom, tabbarItemWidth, TabBar.Frame.Height));
}
else
{
TabBar.SelectionIndicatorImage = _viewModel.Styles.Colors.ActiveTabColor.ToNative().ToImage(new CGRect(0, -View.SafeAreaInsets.Bottom, tabbarItemWidth, TabBar.Frame.Height));
}
}
else
{
TabBar.SelectionIndicatorImage = _viewModel.Styles.Colors.ActiveTabColor.ToNative().ToImage(new CGSize(tabbarItemWidth, TabBar.Frame.Height));
}
UITextAttributes attrs = new UITextAttributes();
attrs.Font = _viewModel.Styles.Fonts.ExtraSmall.ToNative();
attrs.TextColor = _viewModel.Styles.Colors.ActionText.ToNative();
UITabBarItem.Appearance.SetTitleTextAttributes(attrs, UIControlState.Normal);
for (int i = 0; i < TabBar.Items.Length; i++)
{
UITabBarItem item = TabBar.Items[i];
item.Title = _viewModel.Titles[i];
item.TitlePositionAdjustment = new UIOffset(0, -4);
item.ImageInsets = new UIEdgeInsets(-2, 0, 2, 0);
}
//View.LayoutIfNeeded();
}
The button control in xamarin I am using has some very different issue that I haven't met before. The issue is that If I tap on the button very fast and continuously for many times it processing all the taps very slowly. It is visibly irritating that it keep on blinking even after I stopped.
Below is my code
UI Creation Code
QRButton = new Button
{
Text="Title",
TextColor = Color.White,
BackgroundColor = Color.FromHex("#0064A4"),
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.Center,
WidthRequest = 250.0,
BorderRadius = 0
};
//add event handler
QRButton.Clicked += QRButtonPressed;
Button Action
private void QRButtonPressed(object sender, EventArgs e)
{
Console.WriteLine("QR Generation Started");
// Some long running process
Console.WriteLine("QR Generation Completed");
}
The Renderer Implementation
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if(e.NewElement!=null)
{
Control.TitleEdgeInsets = new UIEdgeInsets(4, 4, 4, 4);
Control.TitleLabel.LineBreakMode = UILineBreakMode.WordWrap;
Control.TitleLabel.TextAlignment = UITextAlignment.Center;
}
}
This may be a fairly simple solution but none of the suggestions here work for me. I have a UIScrollView inside a UITableViewCell. I'm adding dynamic images from a list into the scrollview like this.
public void InitViews()
{
scrollViewThumbNails.ContentSize =
new SizeF((float)scrollViewThumbNails.Frame.Size.Width/listCount * listCount,
(float)scrollViewThumbNails.Frame.Size.Height);
for (int i = 0; i < listCount; i++)
{
var imageView = new UIImageView
{
Frame = new RectangleF((float)i * (float)scrollViewThumbNails.Frame.Size.Width / listCount, 0,
(float)scrollViewThumbNails.Frame.Size.Width / listCount, (float)scrollViewThumbNails.Frame.Size.Height),
UserInteractionEnabled = true,
ContentMode = UIViewContentMode.ScaleAspectFit
};
//call method to load the images
var index = i;
imageView.SetImage(
url: new NSUrl(allItems[i].AbsoluteUri),
placeholder: UIImage.FromFile("placeholder.png"),
completedBlock: (image, error, type, url) =>
{
//when download completes add it to the list
if (image != null)
{
allImages.Add(image);
scrollViewThumbNails.AddSubview(imageView);
}
});
}
I found a suggestion here which advices to set the content size of the scrollview, based on the total number of subviews in ViewDidAppear like this:
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
CGRect contentRect = CGRect.Empty;
foreach(UIImageView view in scrollViewThumbNails.Subviews)
{
contentRect = CGRect.Union(contentRect,view.Frame);
}
scrollViewThumbNails.ContentSize = contentRect.Size;
}
The imageViews are still spaced out and do not start from the edge of the screen/scrollview as shown in my screen shot below. I would like for the first image to always be positioned at the origin of the scrollview and wouldn't want the spacing between each image. How can I adjust the scrollview based on the size of its contents?
Can someone show me what I'm missing? Thanks.
I found a solution here where I calculate the total height and width of all the views and assign that as the content size of the scroll view in ViewDidLayoutSubviews:
Solution
public override void ViewDidLayoutSubviews ()
{
base.ViewDidLayoutSubviews ();
try{
float scrollViewHeight = 0.0f;
float scrollViewWidth = 0.0f;
foreach(UIImageView view in scrollViewThumbnails.Subviews)
{
scrollViewWidth += (float)view.Frame.Size.Width;
scrollViewHeight += (float)view.Frame.Size.Height;
}
scrollViewThumbnails.ContentSize = new CGSize(scrollViewWidth, scrollViewHeight);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message+ex.StackTrace);
}
}
I'm having an issue asynchronously loading several UIWebViews into one Section. I'm using MonoTouch.Dialog to generate the UI. I am loading data from a blog and showing 10 items which consist of an image plus some HTML text. What's happening is that the posts are not all showing up and the ones that are showing up are out of order. Here's what I'm doing:
public partial class BlogViewController : DialogViewController
{
private Section mainSection;
public BlogViewController () : base (UITableViewStyle.Grouped, null)
{
Root = new RootElement ("");
mainSection = new Section ("");
mainSection.Add(new ActivityElement ());
Root.Add (mainSection);
}
public override void ViewDidLoad()
{
base.ViewDidLoad ();
new Thread (new ThreadStart(PopulateBlog)).Start ();
}
private void PopulateBlog ()
{
var posts = service.GetPosts (currentOffset, 10);
InvokeOnMainThread (delegate {
foreach (var post in posts) {
//grab an appropriate image size
var altSize = post.photos [0].alt_sizes.Where (x => x.width < 401).OrderByDescending(x => x.width).FirstOrDefault ();
if (altSize != null) {
var img = LoadImageFromUri(altSize.url);
//scale the image, not really important
var imageView = new UIImageView (new RectangleF (0, 0, screenWidth, height));
imageView.Image = img;
var content = new UIWebView ();
//When the HTML finishes rendering figure out the size and add it to the section. Apparently can't figure the size ahead of time?
content.LoadFinished += (sender, e) =>
{
var contentHeight = Int32.Parse (content.EvaluateJavascript ("document.getElementById('content').offsetHeight;"));
content.Frame = new RectangleF (0, height + 10, screenWidth, contentHeight + 10);
//dynamically size this view to fit the content
var view = new UIView
(new RectangleF (0, 0,
screenWidth,
height + contentHeight));
view.AddSubview (content);
view.AddSubview (imageView);
//add the view to the Section which is later added to the Root
mainSection.Add(view);
};
var htmlString = #"some HTML here";
content.LoadHtmlString(someHtml);
content.ScrollView.ScrollEnabled = false;
content.ScrollView.Bounces = false;
}
}
});
Root.Reload(mainSection, UITableViewRowAnimation.None);
}
}
I'm guessing that A) the LoadFinished events are not happening in the same order that they are queued up, and that B) The Root.Reload gets called before they all fire. I tried spinning with a Thread.Sleep prior to the Root.Reload but then the LoadFinished events never even get fired.
I also tried putting all of the UIView elements in a Dictionary to be added after they are all populated but it seems like as soon as InvokeOnMainThread ends the LoadFinished event handler never gets called again.
Do you have to use MT.Dialog? I would personal try to use UITableView instead. Load the web view content, determine its size (maybe use sizeThatFits?) and push it to the data source at correct location. Then return the size on the UITableViewDelegate's heightForRowAtIndexPath call. UITableView should take care of the rest.