我想在聚焦文本框时改变颜色,但是
我收到此错误:
'UIView.Focused'不能分配给它-只读
public UITextField text;
UITextField.Focused += OnFocused
private void OnFocused(object sender, FocusEventArgs focusEventArgs) {
}
答案 0 :(得分:2)
您可以使用以下AttachProperty
:
public static class Attach
{
public static BindableProperty IsFocusedProperty = BindableProperty.Create("IsFocused", typeof(bool), typeof(Attach), false, propertyChanged: OnIsFocusedChanged);
public static void OnIsFocusedChanged(BindableObject bindable, object oldValue, object newValue)
{
var textField = bindable as UITextField;
if(newValue) textField.Focus();
}
}
答案 1 :(得分:1)
您可以使用started
和ended
:
(view as UITextField).Started += focus;
(view as UITextField).Ended += unfocus;
和代表将是:
public static void focus(object sender, EventArgs e)
{
var native = (UITextField)sender;
native.Layer.MasksToBounds = true;
native.Layer.BorderColor = ColorPalette.LightBlue.CGColor;
native.BorderStyle = UITextBorderStyle.RoundedRect;
native.Layer.BorderWidth = 2;
}
public static void unfocus(object sender, EventArgs e)
{
var native = (UITextField)sender;
native.Layer.MasksToBounds = true;
native.Layer.BorderWidth = (System.nfloat)0;
}
答案 2 :(得分:1)
关于 UIView.Focused Property :public virtual bool Focused { get; }
仅具有get方法,因此不能使用UITextField.Focused += OnFocused
,并且会转回错误:'UIView.Focused' cannot be assigned to -- it is read only
如果要在TextField
开始编辑时调用该方法,则可以使用started/ended
来引用x-rw的答案。但是您需要知道此方法来自Xamarin Forms。
在本机iOS中,有一种Delegate
方法可用于了解 UITextField 是否要聚焦。
mtTextField.EditingDidBegin += MtTextField_EditingDidBegin;
mtTextField.EditingDidEnd += MtTextField_EditingDidEnd;
private void MtTextField_EditingDidEnd(object sender, EventArgs e)
{
mtTextField.TextColor = UIColor.Gray;
}
private void MtTextField_EditingDidBegin(object sender, EventArgs e)
{
mtTextField.TextColor = UIColor.Blue;
}
效果:
注意:
您还可以发现,即使正在编辑UITextField
,属性UITextField.Focused
始终都是False
。因此,建议不要使用Focused
来检查UITextField
是否开始编辑。