iOS自定义渲染器中为Xamarin Picker下拉箭头右侧添加内边距
Xamarin Picker iOS自定义渲染器:为右侧下拉箭头添加内边距
我在给Xamarin Picker添加下拉箭头时,已创建自定义iOS渲染器,箭头可正常显示但紧贴Picker右侧,尝试现有代码仍无法解决,如何为箭头右侧添加内边距?
原代码:
protected void UpdateBackground(UITextField control) { if (control == null) return; control.Layer.CornerRadius = ElementV2.CornerRadius; control.Layer.BorderWidth = ElementV2.BorderThickness; control.Layer.BorderColor = ElementV2.BorderColor.ToCGColor(); var downArrowLabel = new UILabel(new CoreGraphics.CGRect(new CoreGraphics.CGPoint(control.Frame.Size.Width - 20 - 16, 0), new CoreGraphics.CGSize(20, control.Frame.Size.Height))); downArrowLabel.Font = UIFont.FromName("FontAwesome", 30); downArrowLabel.Text = "\uf0d7"; downArrowLabel.TextColor = UIColor.Black; downArrowLabel.TextAlignment = UITextAlignment.Center; downArrowLabel.ContentMode = UIViewContentMode.ScaleAspectFit; control.RightView = downArrowLabel; control.RightViewMode = UITextFieldViewMode.Always; control.RightView.Bounds = new CoreGraphics.CGRect(0, 0, 20 + 16, control.Frame.Size.Height); }
当前效果:
解决方法
问题出在RightView的布局逻辑上,直接调整箭头标签的位置容易和UITextField的内置布局冲突,推荐给箭头标签套一个容器视图来控制内边距,代码修改如下:
protected void UpdateBackground(UITextField control) { if (control == null) return; control.Layer.CornerRadius = ElementV2.CornerRadius; control.Layer.BorderWidth = ElementV2.BorderThickness; control.Layer.BorderColor = ElementV2.BorderColor.ToCGColor(); // 创建容器视图,总宽度=箭头宽度+右侧内边距(这里20+16=36) var containerView = new UIView(new CoreGraphics.CGRect(0, 0, 36, control.Frame.Size.Height)); // 创建箭头标签 var downArrowLabel = new UILabel(new CoreGraphics.CGRect(0, 0, 20, control.Frame.Size.Height)); downArrowLabel.Font = UIFont.FromName("FontAwesome", 30); downArrowLabel.Text = "\uf0d7"; downArrowLabel.TextColor = UIColor.Black; downArrowLabel.TextAlignment = UITextAlignment.Center; downArrowLabel.ContentMode = UIViewContentMode.ScaleAspectFit; // 将箭头标签居中放在容器里,容器右侧的空白就是内边距 downArrowLabel.Center = containerView.Center; containerView.AddSubview(downArrowLabel); control.RightView = containerView; control.RightViewMode = UITextFieldViewMode.Always; }
说明
- 容器视图的宽度决定了
RightView占据的总空间,其中超出箭头宽度的部分就是右侧的内边距,你可以根据需求调整容器宽度(比如要更大的内边距就把36改成40) - 这种方式避免了直接计算箭头标签的绝对位置,适配性更强,不会因为Picker的尺寸变化导致布局错乱
内容的提问来源于stack exchange,提问作者scott lafoy
相关产品推荐
相关产品推荐

