我正在创建单选按钮组。 Xamarin.iOS中的内置版本不可用。但是我创建了2个单选按钮,但是两个都是独立的(不像单选按钮组那样) 我一次只需要选择一个选项,并且需要与文本相关的选定单选按钮。 我的代码
public override void ViewDidLoad()
{
base.ViewDidLoad();
var rBtn = new MyRadioButton(new CGPoint(20, 70), "Generic");
this.Add(rBtn);
var rBtn2 = new MyRadioButton(new CGPoint(160, 70), "Subject");
this.Add(rBtn2);
}
MyRadioButton使用了avobe。
public class MyRadioButton : UIView
{
private CircleView circleView;
private UILabel lbTitle;
public bool State {
get {
return circleView.State;
}
set {
circleView.State = value;
}
}
public MyRadioButton (CGPoint pt,string title)
{
this.Frame = new CGRect (pt, new CGSize (150, 30));
circleView = new CircleView (new CGRect(0, 0, 30, 30));
lbTitle = new UILabel (new CGRect (30, 0, 120, 30));
lbTitle.Text = title;
lbTitle.TextAlignment = UITextAlignment.Center;
this.AddSubview (circleView);
this.AddSubview (lbTitle);
this.BackgroundColor = UIColor.FromRGBA(1,0,0,0.3f);
UITapGestureRecognizer tapGR = new UITapGestureRecognizer (() => {
State = !State;
});
this.AddGestureRecognizer (tapGR);
}
}
class CircleView : UIView
{
private bool state = false;
public bool State {
get {
return state;
}
set {
state = value;
this.SetNeedsDisplay ();
}
}
public CircleView (CGRect frame)
{
this.BackgroundColor = UIColor.Clear;
this.Frame = frame;
}
public override void Draw (CoreGraphics.CGRect rect)
{
CGContext con = UIGraphics.GetCurrentContext ();
float padding = 5;
con.AddEllipseInRect (new CGRect (padding, padding, rect.Width - 2 * padding, rect.Height - 2 * padding));
con.StrokePath ();
if (state) {
float insidePadding = 8;
con.AddEllipseInRect (new CGRect (insidePadding, insidePadding, rect.Width - 2 * insidePadding, rect.Height - 2 * insidePadding));
con.FillPath ();
}
}
}
请参见下面的输出屏幕截图,我可以选择两个单选按钮。他们的行为不像小组