LoginSignup
2
7

More than 5 years have passed since last update.

Xamarinでカスタムコントロールを作成

Posted at

iOS

クラス定義の例

UIButtonを継承して、枠線ありのボタンを作ってみる。

BorderButton.cs
using System;
using System.ComponentModel;
using Foundation;
using UIKit;
using CoreGraphics;

namespace MyApp.iOS
{
    [Register("BorderButton"), DesignTimeVisible(true)]
    public class BorderButton : UIButton
    {
        [Export("BorderRadius"), Browsable(true)]
        public nfloat BorderRadius { get; set; }

        [Export("BorderWidth"), Browsable(true)]
        public nfloat BorderWidth { get; set; }

        [Export("BorderColor"), Browsable(true)]
        public UIColor BorderColor { get; set; }

        public BorderButton() : base() { }
        public BorderButton(IntPtr handle) : base(handle) { }

        public override void Draw(CGRect rect)
        {
            this.Layer.CornerRadius = this.BorderRadius;
            this.Layer.BorderWidth = this.BorderWidth;
            this.Layer.BorderColor = this.BorderColor.CGColor;
            base.Draw(rect);
        }
    }
}

各行の解説

[Register("BorderButton"), DesignTimeVisible(true)]

Registerを設定すると、Classにカスタムコントロールのクラスを指定できるようになる。

identity.png

DesignTimeVisibleを設定して、かつコンストラクタを定義すると、ツールボックスに"Custom Components"が出現する。

public BorderButton() : base() { }
public BorderButton(IntPtr handle) : base(handle) { }

toolbox.png

Exportを設定すると、カスタムプロパティが出現する。

[Export("BorderRadius"), Browsable(true)]
public nfloat BorderRadius { get; set; }

[Export("BorderWidth"), Browsable(true)]
public nfloat BorderWidth { get; set; }

[Export("BorderColor"), Browsable(true)]
public UIColor BorderColor { get; set; }

custom_prop.png

drawRectの代わりに、Drawをオーバーライドして領域を描画する。

public override void Draw(CGRect rect)
{
    this.Layer.CornerRadius = this.BorderRadius;
    this.Layer.BorderWidth = this.BorderWidth;
    this.Layer.BorderColor = this.BorderColor.CGColor;
    base.Draw(rect);
}

XamarinではdrawRectの代わりにDrawが呼ばれる模様。

DrawRect never called for custom view:
https://forums.xamarin.com/discussion/60934/drawrect-never-called-for-custom-view

と、ここまでやるとstoryboardでカスタムコントロールを配置可能になる。

border_button.png

こちらを参考にしました。
http://qiita.com/hatapu/items/99e6a8b19f890f0fec9f

Android

まだ。

2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7