我正在尝试设置Xamarin.Forms SearchBar的样式,并且可以看到存在BackgroundColor属性,但是无论设置什么,该属性在iOS中都会被忽略。
甚至可以在iOS中自定义Xamarin.Forms SearchBar(以及如何)?
据我所知,Xamarin.Forms不具有实现BackgroundColor属性的属性,或者它已损坏。最接近真实背景颜色的UISearchBar属性是BarTint,它不是XForms设置的。
为了解决这个问题,我认真考虑了这些注释,并使用自定义渲染器创建了自己的自定义SearchBar,以扩展BarTint属性以及我想要的其他一些功能。
注意:为了使用自定义渲染器,请确保您已更新到Xamarin.Forms 1.1.1.6206或更高版本。要更新平台版本,请使用Visual Studio中的NuGet或XamarinStudio中的内置程序包管理器。
您将需要两个类,第一个是CustomSearchBar,UI将使用它来保存自定义属性。它放在共享或可移植的类库中。:
using Xamarin.Forms;
namespace App1
{
public class CustomSearchBar : SearchBar
{
// Use Bindable properties to maintain XAML binding compatibility
public static readonly BindableProperty BarTintProperty = BindableProperty.Create<CustomSearchBar, Color?>(p => p.BarTint, null);
public Color? BarTint
{
get { return (Color?)GetValue(BarTintProperty); }
set { SetValue(BarTintProperty, value); }
}
public static readonly BindableProperty SearchStyleProperty = BindableProperty.Create<CustomSearchBar, string>(p => p.SearchStyle, "Default");
public string SearchStyle
{
get { return (string)GetValue(SearchStyleProperty); }
set { SetValue(SearchStyleProperty, value); }
}
public static readonly BindableProperty BarStyleProperty = BindableProperty.Create<CustomSearchBar, string>(p => p.BarStyle, "Default");
public string BarStyle
{
get { return (string)GetValue(BarStyleProperty); }
set { SetValue(BarStyleProperty, value); }
}
}
}
第二类是自定义渲染器本身,它可以访问本机UISearchButton控件。此类进入iOS项目:
using System;
using System.Drawing;
using App1;
using App1.iOS;
using MonoTouch.UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRendererAttribute(typeof(CustomSearchBar), typeof(CustomSearchBarRenderer))]
namespace App1.iOS
{
public class CustomSearchBarRenderer : SearchBarRenderer
{
// There might be a better place for this, but I don't know where it is
public override void Draw(RectangleF rect)
{
var csb = (CustomSearchBar) Element;
if (csb.BarTint != null)
Control.BarTintColor = csb.BarTint.GetValueOrDefault().ToUIColor();
Control.BarStyle = (UIBarStyle)Enum.Parse(typeof(UIBarStyle), csb.BarStyle);
Control.SearchBarStyle = (UISearchBarStyle)Enum.Parse(typeof(UISearchBarStyle), csb.BarStyle);
base.Draw(rect);
}
}
}
代码有点粗糙,但希望您能理解。
另外一些注意事项:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句