iOS keep keyboard open when tab a specific element - ios

I have a UITextView and a Button.
I need that the keyboard stays opened when the user taps the button.
I tried to use the ShouldEndEditing function to return False, but then the user can never close the keyboard again.
Any ideas?
I'm using Xamrin Forms.

In Objective-C you would set a Done Editing event in the view controller, which would immediately re-open the keyboard.. with no visual change.
-(IBAction) textFieldDoneEditing : (id) sender{
[sender resignFirstResponder];
[sender becomeFirstResponder];
}
Xamarin / C# equivalent.. off the top of my head.
txtMyTextBox.Ended += (sender, e) =>
{
txtMyTextBox.ResignFirstResponder();
txtMyTextBox.BecomeFirstResponder();
};

Ah, interesting question and you have already known about the property "ShouldEndEditing" in UITextFieldDelegate, so why don't you try to implement a custom delegate for your UITextField?
I wrote a sample for you and I use a UISwitch to simulate the condition for hiding the keyboard, in your ViewController, use the code below:
public override void ViewDidLoad ()
{
MYTextFieldDelegate myDel = new MYTextFieldDelegate ();
UITextField textTF = new UITextField ();
textTF.Frame = new CoreGraphics.CGRect (50, 50, 200, 40);
textTF.BackgroundColor = UIColor.Red;
textTF.Delegate = myDel;
this.Add (textTF);
UIButton btnTest = new UIButton (UIButtonType.System);
btnTest.SetTitle ("Test", UIControlState.Normal);
btnTest.Frame = new CoreGraphics.CGRect (50, 100, 200, 40);
btnTest.TouchUpInside += delegate {
this.View.EndEditing (true);
};
this.Add (btnTest);
UISwitch keyboardSwitch = new UISwitch ();
keyboardSwitch.Frame = new CoreGraphics.CGRect (50, 150, 200, 40);
keyboardSwitch.ValueChanged += (sender, e) => {
bool flag = (sender as UISwitch).On;
myDel.FlagForDisplayKeyboard = flag;
};
this.Add (keyboardSwitch);
}
And this is MYTextFieldDelegate.cs:
class MYTextFieldDelegate : UITextFieldDelegate
{
public bool FlagForDisplayKeyboard { get; set; }
public override bool ShouldEndEditing (UITextField textField)
{
return FlagForDisplayKeyboard;
}
public MYTextFieldDelegate ()
{
FlagForDisplayKeyboard = false;
}
}
Hope it can help you.

Related

UIPickerView not interactive

I have an application that from the main app "hamburger" menu, if an option is selected I want to show a PickerView for the user to select a number from.
Because it's needs to be accessible throughout the app from this menu I built the UIPickerView in the AppDelegate.cs (as that's where the UINavigationController code is and from that the menu).
Everything shows up correctly: User selected menu button -> menu displays -> User selects "Show Picker" button -> Picker displays with all items. But once the picker displays, you can't scroll the options, nor does the "Done" button I've added register clicks. In fact text fields from the ViewController behind this popup can be clicked on through the popup.
I'm not sure why this UIPickerView is non interactive, does anyone have some thoughts?
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow(UIScreen.MainScreen.Bounds);
// instantiate the navigation controller
nav = new UINavigationController(new SplashController());
vwNav = new UIView(nav.NavigationBar.Bounds);
var pickerView = new UIPickerView(new CGRect(275f, (UIScreen.MainScreen.Bounds.Size.Height / 2) - (375f / 2), 275f, 375f));
pickerView.ShowSelectionIndicator = true;
var myPickerViewModel = new PickerViewModel(itemList);
pickerView.Model = myPickerViewModel;
myPickerViewModel.PickerChanged += (sender, e) => {
var temp = myPickerViewModel.SelectedItem;
};
// Set up toolbar
var toolbar = new UIToolbar();
toolbar.SizeToFit();
toolbar.Hidden = false;
UILabel titleLabel = new UILabel();
titleLabel.Text = "Select an Item";
titleLabel.Frame = new RectangleF(75, 13, 200, 20);
UIButton doneButton = new UIButton(UIButtonType.Custom);
doneButton.Frame = new RectangleF(40, 335, (float)200, 30);
doneButton.SetTitle("Done", UIControlState.Normal);
doneButton.TouchDown += (sender, e) =>
{
pickerView.Hidden = true;
};
toolbar.AddSubview(titleLabel);
toolbar.AddSubview(doneButton);
pickerView.AddSubview(toolbar);
pickerView.Hidden = true;
btnMenu = new UIButton(UIButtonType.Custom);
btnMenu.Frame = new CGRect(vwNav.Frame.Right - 45, 0, 45, nav.NavigationBar.Bounds.Height);
btnMenu.SetImage(imgMenu, UIControlState.Normal);
btnMenu.SetImage(imgMenu, UIControlState.Selected);
btnMenu.TouchUpInside += (object sender, EventArgs e) =>
{
UIAlertView alert = new UIAlertView();
alert.Title = "Settings";
alert.AddButton("Open PickerView");
alert.AddButton("Exit");
alert.Dismissed += delegate (object alertSender, UIButtonEventArgs args)
{
if (args.ButtonIndex == 0)
{
pickerView.Hidden = false;
}
else
return;
}
}
vwNav.AddSubviews(btnMenu, pickerView);
nav.NavigationBar.Layer.BorderWidth = 2f;
nav.NavigationBar.Layer.BorderColor = (UIColor.FromPatternImage(imgNavBar)).CGColor;
nav.NavigationBar.AddSubviews(vwNav);
// If you have defined a root view controller, set it here:
this.window.RootViewController = nav;
this.window.MakeKeyAndVisible();
return true;
}
I removed some of the unrelated code (a few nav.PushViewController() for different screens and other menu options) to keep it as clear as I could.
From your code, the frame of vwNav is nav.NavigationBar.Bounds, and the frame of pickerView is new CGRect(275f, (UIScreen.MainScreen.Bounds.Size.Height / 2) - (375f / 2), 275f, 375f), if you add pickView to vwNav, the pickerView is out of bounds of vwNav.
Remember that views don't receive touch events where they're outside the bounds of their superview.
That's the cause of your issue.
Solution:
I don't think you should built the UIPickerView in the AppDelegate.cs, create it in your ViewController instead.
You can also add buttons to Navigationbar in ViewController :
UIBarButtonItem btn = new UIBarButtonItem();
btn.Image = UIImage.FromFile("Image");
btn.Clicked += (sender, e) => { System.Diagnostics.Debug.WriteLine("show picker"); };
NavigationItem.RightBarButtonItem = btn;
And remember to add picker to the View of Viewcontroller.
Refer: uinavigationitem and add-uibarbuttonitem-to-navigation-bar-in-xamarin-ios
Feel free to ask me any question:).

iOS : View visible but not active

I got a UIViewController that init a UIView.
This view containing Interactive Elements like UITextField or UIButton.
View is added on ViewDidLoad, at the bottom of the method to be sure that when I made it visible it can be reach by user interaction.
But when I show the view, no interaction can be done on this View.
Is this only possible? Am I doing something wrong?
The View
public class AddBusinessEventView : UIView
{
public UILabel LblTitle;
public UITextField TxtType;
public UIButton BtnClose;
public AddBusinessEventView(nfloat bw, nfloat bh)
{
//Bouton pour fermer le popup
BtnClose = new UIButton();
BtnClose.SetImage(UIImage.FromFile("Images/Boutons/lightbox_close.png"), UIControlState.Normal);
BtnClose.Frame = new CGRect(bw - 80, 30, BtnFermer.ImageView.Image.CGImage.Width * 0.5, BtnFermer.ImageView.Image.CGImage.Height * 0.5);
//Doit se trouver par dessus txtSite et ajouté après dans la vue pour se trouvé en premier plan
LblTitle = new UILabel();
LblTitle.Frame = new CGRect((bw - (lw + 200)) / 2, 100, lw + 200, 30);
LblTitle.Text = "Fill with your event elements";
LblTitle.Font = UIFont.FromName("GillSans-Bold", 22);
LblTitle.TextColor = UIColor.FromRGB(211, 3, 67);
LblTitle.TextAlignment = UITextAlignment.Center;
TxtType = new UITextField(new CGRect((bw - 750) / 2, 140, 350, 40));
TxtType.BackgroundColor = UIColor.White;
TxtType.TextAlignment = UITextAlignment.Center;
TxtType.BorderStyle = UITextBorderStyle.RoundedRect;
TxtType.AutocorrectionType = UITextAutocorrectionType.No;
TxtType.AutocapitalizationType = UITextAutocapitalizationType.AllCharacters;
TxtType.Placeholder = "Type";
AddSubviews(BtnClose, LblTitle, TxtType);
}
}
The UIViewController
partial class EvenementViewController : EnhancedUIViewController
{
AddBusinessEventView AddBusinessEventView;
public EvenementViewController(IntPtr handle) : base(handle) { }
public EvenementViewController() : base() { }
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
if (myEvent == null)
{
ShowAddBusinessEventView();
}
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
nfloat bw = View.Bounds.Width;
nfloat bh = View.Bounds.Height;
//Another Elements are adding to view here
//...
AddBusinessEventView = new AddBusinessEventView(bw, bh);
AddBusinessEventView.Hidden = true;
//Much more View.Add with all elements here
//...
View.Add(AddBusinessEventView);
AddBusinessEventView.BtnType.TouchUpInside += BtnClose_TouchUpInside;
}
#region BusinessEventAdd
void ShowAddBusinessEventView()
{
UIView.Animate(duration: 1,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animation: () =>
{
AddBusinessEventView.Alpha = 1.0f;
},
completion: () =>
{
AddBusinessEventView.Hidden = false;
AddBusinessEventListener();
}
);
}
void HideAddBusinessEventView()
{
UIView.Animate(duration: 1,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animation: () =>
{
AddBusinessEventView.Alpha = 0.0f;
},
completion: () =>
{
AddBusinessEventView.Hidden = true;
RemoveBusinessEventListener();
}
);
}
void BtnClose_TouchUpInside(object sender, EventArgs e)
{
System.Diagnostics.Debug.Print("Touching myself");
}
#endregion
}
please concidere EnhancedViewController as standard UIViewController, I'm juste adding some enhancements to show users a message from an Overlay.
As I said, we can't interact neither with TxtType nor BtnClose.
Edit :
Don't sure if it can help; but when the View is added to the Main View on the UIViewController, it display well, but all user interaction are catches on element under this View
i.e : The AddBusinessEventView act as a popup, so it covered all other element, when i press an element, if another element adding prior of this View is under, it's this element rather than the AddBusinessEventView element that catch the touch event.
As said, the main purpose is to cut View element on different file for more readability and maintenability of this application.enter code here
There is no reason you can't do that.
You can architect your code like
UIViewController
Controller1
Controller2
...
Views
View1
View2
...
And then use View1 and View2 in any of Controller.
I tried your code and I got all the things popup correctly.
As you said, if view show up on screen but it's element from another View from below that interact with user maybe you can try to bring your View to front.
Try this
View.BringSubviewToFront(AddBusinessEventView);
At the end of your ViewDidLoad function.

mvvmcross N-06-Books Sample How to change Tableview size after loading?

Stuart's N-06 Books sample is good for getting basic understanding about using MvxSimpleTableViewSource.
[Register("FirstView")]
public class FirstView : MvxViewController
{
public override void ViewDidLoad()
{
View = new UIView(){ BackgroundColor = UIColor.White};
base.ViewDidLoad();
// ios7 layout
if (RespondsToSelector(new Selector("edgesForExtendedLayout")))
EdgesForExtendedLayout = UIRectEdge.None;
var textField = new UITextField(new RectangleF(10, 10, 300, 40));
Add(textField);
var tableView = new UITableView(new RectangleF(0, 50, 320, 500), UITableViewStyle.Plain);
Add(tableView);
tableView.RowHeight = 88;
var source = new MvxSimpleTableViewSource(tableView, BookCell.Key, BookCell.Key);
tableView.Source = source;
var set = this.CreateBindingSet<FirstView, Core.ViewModels.FirstViewModel>();
set.Bind(textField).To(vm => vm.SearchTerm);
set.Bind(source).To(vm => vm.Results);
set.Apply();
tableView.ReloadData();
}
}
But how can resize the tableview's height according it's content once it loads data?
Not entirely sure what you want to do... Normally in an iOS UI, the tableview size is fixed regardless of its content.
However, if you did want to resize the table then you could:
Inherit from MvxTableViewSource or UITableView and provide some logic there
Or add a binding in your class to some View property TableCount, bind that property and then implement the sizing logic there. Something like:
set.Bind(this).For(v => v.TableCount).To(vm => vm.Results.Count);
private int _tableCount
public int TableCount {
get { return _tableCount; }
set {
// implement your sizing animations here (maybe animate constraints?)
}
}
Just to add to Stuart's answer, here is an example for the frame of the table:
int _tableHeight;
public int TableHeight
{
get { return _tableHeight; }
set
{
_tableHeight = value;
_myPlayers.Frame = _tableHeight > 0 ? new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, Dimens.TableRowHeight * _tableHeight) : new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, Dimens.TableRowHeight * BusinessConstants.GetBiggestPositionCount());
_myPlayers.ReloadData();
}
}

Is there any custom date picker for iOS where year selection is optional?

I need to be able to select day and month and leave the option to the user to select the year or not. For example I was thinking a list with all the years and at the end an added option "no selection".
Any ideas how to do that?
I suppose that using the picker view is one solution but not sure.
Thanks
Using xamarin.ios what I did was create a toolbar on top of the thumbwheel with a Done and a Cancel buttons. When you click done the value is set, and you click cancel what you need to do is set the Datepicker value to a value like 1900-1-1 and change the uitextfield value to something like "Not set".
I'm using xamarin forms. This is what I have in my custom renderer:
public override void Draw (CGRect rect)
{
base.Draw (rect);
DatePicker elem = (DatePicker)Element;
UITextField textField = (UITextField)Control;
var toolbar = new UIToolbar(new CGRect(0.0f, 0.0f, Control.Frame.Size.Width, 44.0f));
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.Cancel,(object sender, EventArgs e) => {
if (elem.SetValueNullAction!=null){
elem.SetValueNullAction();
textField.Text = DefaultNotSetText;
}
}),
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
new UIBarButtonItem(UIBarButtonSystemItem.Done,(object sender, EventArgs e) => {
elem.Unfocus();
})
};
textField.InputAccessoryView = toolbar;
textField.BorderStyle = UITextBorderStyle.None;
textField.TextColor = Color.FromHex ("999999").ToUIColor ();
CGRect frame = textField.Frame;
frame.Width = 100;
textField.Frame = frame;
if (elem.Date == elem.MinimumDate) {
textField.Text = ((DatePicker)this.Element).Label;
}
}
Hope this helps!
You can have a try of CKPickerView, it allows very easy customization on UIDatePicker.

How to hide a UIView and remove the "empty" space? -iOS/Monotouch

I need to be able to hide controls on a page that uses constraints and remove the empty space that Hidden=true leaves. It needs to be similar to how the web handles visibility. If it's invisible, it doesn't take up space.
Does anyone know of a clean way to accomplish this?
Please let me know if you need more details.
Thx
Example:
UIButton | UIButton | UIButton
"empty space for hidden UIButton"
UIButton
That should really be rendered like this:
UIButton | UIButton | UIButton
UIButton
Edit: I'm using Xamarin Studio and VS2012 for development.
Since original question is related to Xamarin, I provide complete C# solution.
First, create height constraint for your view and give it an identifier in Xcode Interface Builder:
Then in controller override ViewDidAppear() method and wrap view with HidingViewHolder:
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
applePaymentViewHolder = new HidingViewHolder(ApplePaymentFormView, "ApplePaymentFormViewHeightConstraint");
}
It is important to create HidingViewHolder when view was laid out, so it has real height assigned.
To hide or show view you can use corresponding methods:
applePaymentViewHolder.HideView();
applePaymentViewHolder.ShowView();
HidingViewHolder source:
using System;
using System.Linq;
using UIKit;
/// <summary>
/// Helps to hide UIView and remove blank space occupied by invisible view
/// </summary>
public class HidingViewHolder
{
private readonly UIView view;
private readonly NSLayoutConstraint heightConstraint;
private nfloat viewHeight;
public HidingViewHolder(UIView view, string heightConstraintId)
{
this.view = view;
this.heightConstraint = view
.GetConstraintsAffectingLayout(UILayoutConstraintAxis.Vertical)
.SingleOrDefault(x => heightConstraintId == x.GetIdentifier());
this.viewHeight = heightConstraint != null ? heightConstraint.Constant : 0;
}
public void ShowView()
{
if (!view.Hidden)
{
return;
}
if (heightConstraint != null)
{
heightConstraint.Active = true;
heightConstraint.Constant = viewHeight;
}
view.Hidden = false;
}
public void HideView()
{
if (view.Hidden)
{
return;
}
if (heightConstraint != null)
{
viewHeight = heightConstraint.Constant;
heightConstraint.Active = true;
heightConstraint.Constant = 0;
}
view.Hidden = true;
}
}
In storyboard wire your constrains first. Then try this
self.viewToHideHeight.constant = 0;
self.lowerButtonHeightFromTop.constant = self.viewToHideHeightFromTop.constant + self.viewToHideHeight.constant;
[UIView animateWithDuration:0.5f animations:^{
self.viewToHide.alpha = 0.0f;
[self.view layoutIfNeeded];
}];

Resources