2017-10-10 43 views
1

有沒有辦法將子類UIButton指定爲UIButtonType使用特定的UIButtonType子類化UIButton

我想在設計器中使用我的按鈕類,並設置類型。

+0

你可以繼承它裏面和AwakeFromNib()方法,你可以設置默認的類型。但是據我所知,如果我錯了,糾正我,沒有真正的方法來在Designer中使用該按鈕,期望你看到默認的按鈕並設置類。但是如果你想自己繪製並在設計器中顯示,那麼沒有辦法 –

+0

嗨,我的回答是否可以幫助你? –

+0

'ButtonType'是隻讀屬性,所以我不認爲你可以設置它。關於在設計器中使用,我的意思是像你創建自定義按鈕類,然後在設計器中分配該類到你的按鈕。 – Naomak

回答

1

由於UIButtonType是隻讀屬性,因此無法執行此操作。

只有兩個場景中的子類UIButton

  1. 創建的UIButton的子類,創建一個公共的方法來包裝它的初始方法。

    public class MyButton : UIButton 
    { 
        public static MyButton CreateButton() 
        { 
         return UIButton.FromType(UIButtonType.Custom) as MyButton; 
        } 
    } 
    

    用法:

    MyButton button = MyButton.CreateButton(); 
    

    您只能使用它的代碼沒有設計這樣

  2. 從設計師創建一個按鈕,並重新命名它的類 enter image description here

    它會自動生成名爲CustomButton的UIButton的子類文件夾,並且可以將其分配給設計器中的其他按鈕。

    enter image description here

    但正如我上面提到的,UIButtonType是一個只讀屬性,沒有辦法去改變它,一旦它的設置。

    public partial class CustomButton : UIButton 
    { 
        public CustomButton (IntPtr handle) : base (handle) 
        { 
         this.ButtonType = UIButtonType.Custom; //incorrect , read-only 
    
         this.Font = UIFont.SystemFontOfSize(10); //correct, read-write 
        } 
    } 
    

    RE:Change UIButton type in subclass if button created from storyboard

+0

感謝您的好回答。是的,我也發現了兩種可能性。我只是想知道,如果還有其他的方式。我想用你在第二個答案中描述的方式使用它,很遺憾你不能這樣做:/ – Naomak