Reputation: 197
While in entry focus, I cannot unfocus by clicking anywhere on the screenthe only way to unfocus entry is click return button on keyboard. How can I unfocus an Entry in a NET MAUI application, particularly on iOS, when the user clicks outside the entry or anywhere else on the screen?
Upvotes: 3
Views: 2139
Reputation: 56
I used this code on Android to do the trick. I did not yet find any solution for iOS.
public class MainActivity : MauiAppCompatActivity
{
// Other Code
public override bool DispatchTouchEvent(MotionEvent? e)
{
if (e!.Action == MotionEventActions.Down)
{
var focusedElement = CurrentFocus;
if (focusedElement is EditText editText)
{
var editTextLocation = new int[2];
editText.GetLocationOnScreen(editTextLocation);
var clearTextButtonWidth = 100;
var editTextRect = new Rect(editTextLocation[0], editTextLocation[1], editText.Width + clearTextButtonWidth, editText.Height);
var touchPosX = (int)e.RawX;
var touchPosY = (int)e.RawY;
if (!editTextRect.Contains(touchPosX, touchPosY))
{
editText.ClearFocus();
var inputService = GetSystemService(Context.InputMethodService) as InputMethodManager;
inputService?.HideSoftInputFromWindow(editText.WindowToken, 0);
}
}
}
return base.DispatchTouchEvent(e);
}
}
Upvotes: 1
Reputation: 1807
Set HideSoftInputOnTapped="True"
on your ContentPage
.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
HideSoftInputOnTapped="True"
x:Class="MyApp.MainPage">
<Entry />
</ContentPage>
Upvotes: 6