Xamarin.ios Custom Button Selector

Source: Internet
Author: User
Tags uikit

Recent project has done a button selector in the title bar, the original Uisegmentedcontrol can not achieve the project effect, the effect of the following figure:

If it is not difficult to write only for the project, but if you encounter a later need to write a project, so I intend to write his live some, and finally decided to use the builder mode to complete it, before doing Android native to use builder mode to build some combination view, But I try to use the Java way to builder when found not workable, this is Xamarin project, language is C #, so I went to learn the C # Builder mode (simple understanding is very easy).

Oh, almost forgot to introduce, the framework of the project is Mvvmcross, do not understand the classmate to his official website to see, very conscience.

Finally, it's planned. This work is divided into three steps (typical process-oriented, haha).



The first step is to abstract these visible attributes, or properties that can be changed at any time.

Using System;
Using Uikit;

Namespace Ruilaigrow.ios
{
    ///<summary>
    ///Multi-button rounded view build abstract class
    ///by GE
    ///</summary>
    Abstract class Buildertopselectedtitle
    {public
        abstract void Settitles (string[] titles);
        public abstract void Settextsize (nfloat size);
        public abstract void Setcornerradius (nfloat radius);
        public abstract void SetHeight (nfloat height);
        public abstract void SetWidth (nfloat width);
        public abstract void Setnormaltextcolor (uicolor color);
        public abstract void Setselectedtextcolor (uicolor color);
        public abstract void Setviewbackground (Uicolor background);
        public abstract void Setitemnormal (Uicolor corlor);
        public abstract void setitemselected (Uicolor selected);
        Public abstract UIView Create ();
    }


The project is more nervous, perhaps these attributes are not enough, or think of not in place, and then slowly add and optimize.


Step Two: Create the implementation class and build the controls you need.

After some research, the outermost (that is, the final creation returned to the interface) is a uiview, the middle button is replaced by UIButton, because: after looking at the material, and trying to find out, UIButton is uilable in the Uiimageview package of results, Lazy to load the way, with who to initialize who, it feels great I don't have to build my own wheels (I used to be an android native, I don't know much about iOS, we laughed). The following is the implementation of the class code, the gaze is very full, direct copy and paste (lazy lazy).

Using System;
Using System.Drawing;
Using RuilaiGrow.iOS.Common;

Using Uikit; namespace Ruilaigrow.ios {///<summary>///KB Home page title Toggle Controller///</summary> class Knowledgetitlec Ontrol:buildertopselectedtitle {public Knowledgetitlecontrol () {}//
        The outermost total view uiview _thisview = null;
                    Public UIView Thisview {get {if (_thisview = null) { Based on the width and height of the view, the position is computed (the goal is eventually added to the view's navigation bar to be centered) nfloat StartX = (uiscreen.mainscreen. Bounds.width-_itemwid * _titles.
                    Length)/2;
                    Nfloat Starty = (Easylayout.barheight-_viewhei)/2; _thisview = new UIView (new RectangleF (float) startx, (float) starty, (_itemwid * _titles.
                    Length), (float) _viewhei);
                _thisview.backgroundcolor = _viewbackground;
  return _thisview;          }//header array private string[] _titles;

        Item array private uibutton[] _itembtns;

        Control of the high private nfloat _viewhei = 45;

        Item's wide private nfloat _itemwid = 70;

        Item normal color private Uicolor _itemnormalbac = Uicolor.blue;

        Item when selected color private uicolor _itemseletedbac = Uicolor.white;

        The normal color of the text private uicolor _textnormalcolor = Uicolor.black;

        The color when text is selected private Uicolor _textseletedcolor = uicolor.red;

        Set the color of this view private uicolor _viewbackground = Uicolor.blue;

        The size of the text private nfloat _textsize = 15;

        Border and Button rounded corner private nfloat _radius = 18;

        Button Last Click event Default 0 private int lastindex = 0;
            <summary>///Ultimately create view///</summary> public override UIView Create () {
            ThisView.Layer.BorderWidth = 1; ThisView.Layer.BoRdercolor = MvxTouchColor.ShallowGrayOne.CGColor;

            ThisView.Layer.CornerRadius = _radius; _itembtns = new Uibutton[_titles.

            Length]; Loop to create the text button and add it to the total view int lenght = _titles.
            Length;
                for (int i = 0; I < lenght i++) {_itembtns[i] = new UIButton (); _itembtns[i].
                Tag = i; _itembtns[i].
                Settitle (_titles[i], uicontrolstate.normal); _itembtns[i].
                Settitlecolor (_textnormalcolor, uicontrolstate.normal); _itembtns[i].
                Layer.cornerradius = _radius; _itembtns[i].
Titlelabel.font = Uifont.systemfontofsize (_textsize); Sets the first button selected state if (i = = 0) {_itembtns[i].
                    BackgroundColor = _itemseletedbac; _itembtns[i].
                Settitlecolor (_textseletedcolor, uicontrolstate.normal);

            } thisview.addsubviews (_itembtns);
   Loop set constraint between view internal item         for (int i = 0; I < lenght i++) {if (i = = 0) {Thisview. Constrainlayout (() => _itembtns[i]. Frame.getcentery () = = ThisView.Frame.GetCenterY () && _itembtns[i]. Frame.width = = _itemwid && _itembtns[i]. Frame.height = = ThisView.Frame.Height && _itembtns[i]. Frame.left = = ThisView.Frame.Left && ThisView.Frame.Bottom = = _itemb Tns[i].
                Frame.bottom);
                                             else {thisview.constrainlayout () => _itembtns[i]. Frame.getcentery () = = ThisView.Frame.GetCenterY () && _itembtns[i]. Frame.left = = _iteMBTNS[I-1]. Frame.right && _itembtns[i]. Frame.width = = _itemwid && _itembtns[i].
                Frame.height = = ThisView.Frame.Height); }//button click event for (int i = 0; i < _titles. Length; i++) {_itembtns[i]. Touchupinside = this.
            TOUCHBTN;
        return thisview; //button click handle private void Touchbtn (object sender, EventArgs e) {UIButton v = (uikit.ui

            Button) sender;

            If the same as the last point return if (V.tag = = lastindex) return; Empty the last click View state _itembtns[lastindex].
            BackgroundColor = _itemnormalbac; _itembtns[lastindex].

            Settitlecolor (_textnormalcolor, uicontrolstate.normal); Set the status of this click View _itembtns[v.tag]. BackgroundColor = _itemseletedbac;
            _itembtns[v.tag].

            Settitlecolor (_textseletedcolor, uicontrolstate.normal);

            Record the position of this click lastindex = (int) V.tag; Callback Click Position if (_click!= null) {_click.
            Titlebackindex ((int) v.tag); }///<summary>///the status color///</summary>///<param name= When the button is set to normal "Corlor" >Corlor.</param> public override void Setitemnormal (Uicolor corlor) {this._i
        Temnormalbac = Corlor; ///<summary>///Set the background///</summary>///<param name= "selected" When Item is selected >Selected.</param> public override void Setitemselected (Uicolor Selected) {This._ite
        Mseletedbac = selected; ///<summary>///Set the color of the text when normal///</summary>///<param name= "Color" > color.</param> public override void SetnormaltExtcolor (uicolor color) {this._textnormalcolor = color; ///<summary>///Sets the color of the text when selected///</summary>///<param name= "Color" >c olor.</param> public override void Setselectedtextcolor (Uicolor color) {This._textselet
        Edcolor = color; ///<summary>///Set the text of the item///</summary>///<param name= "titles" >t
        itles.</param> public override void Settitles (string[] titles) {this._titles = titles; ///<summary>///Set view background picture///</summary>///<param name= "ba
            Ckground ">Background.</param> public override void Setviewbackground (Uicolor Background) {
        This._viewbackground = background; ///<summary>///Set the item's width///</summary>///<param name= "Width ">Width.</param> public override void SetWidth (Nfloat Width) {this._itemwid = W
        Idth; ///<summary>///Set the high///</summary>///<param name= "height" of this view >h
        eight.</param> public override void SetHeight (nfloat height) {this._viewhei = height; ///<summary>///Set the rounded corners of the border with the rounded corners of the button///</summary>///<param name= "R Adius ">Radius.</param> public override void Setcornerradius (Nfloat Radius) {This._ra
        Dius = radius; ///<summary>///Sets the size of the text///</summary>///<param name= "Size" >size.
        </param> public override void Settextsize (nfloat size) {this._textsize = size; }///<summary>///Click View Callback Interface///</summary> public interface CLicktitlecontrolitem {void titlebackindex (int index);

        Private Clicktitlecontrolitem _click;
        public void Setclicktitlecontrolitem (Clicktitlecontrolitem click) {this._click = click; }
    
    }
}



The above is the implementation of the entire class, the last interface is this view click on a button callback, colleagues said I this is to take the idea of Java to write C #, I went to check, I intend to change this into an event-entrusted mechanism.

Let's take a look at the third step: using

Directly defining a UIView in controller to receive the created view can:

 View UIView _topviewcontrol = null for the head navigation bar; Public UIView Topviewcontrol {get{if (_topviewcontrol = = null) {string
                    [] s = new string[] {"0-1 years old", "1-3 years old", "3-6 years old"};
                    Knowledgetitlecontrol ctr = new Knowledgetitlecontrol ();
                    Ctr.setwidth (85);
                    Ctr.setheight (easylayout.barheight-10f);
                    Ctr.settitles (s);
                    Ctr.settextsize (15);
                    Ctr.setcornerradius (18);
                    Ctr.setitemnormal (mvxtouchcolor.deepred);
                    Ctr.setviewbackground (mvxtouchcolor.deepred);
                    Ctr.setitemselected (Mvxtouchcolor.white);
                    Ctr.setnormaltextcolor (Mvxtouchcolor.shallowgrayone);
                    Ctr.setselectedtextcolor (mvxtouchcolor.deepred);
                    Ctr.setclicktitlecontrolitem (this); _topviewcontroL = ctr.create ();
            return _topviewcontrol; }
        }



Finally, you can add the view to the navigation bar:

In the Viewdidload () method:

Add the head controller's UIView to the top navigation bar
NavigationController.NavigationBar.AddSubview (Topviewcontrol);

The number of buttons is determined by the array passed in by the constructor.

Get..




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.