2014-08-31 63 views
0

我想初始化一個自定義的UIButton類,但我做錯了,不知道如何實現這個。我建立了一個自定義的UIButton類,並在IBOutlet中初始化它。該按鈕工作正常,但沒有我設置的屬性顯示。構建用邊界初始化的UIButton

import UIKit 
import Foundation 

class WBCircleButton : UIButton { 
required init(coder aDecoder: NSCoder) { 
    super.init(coder: aDecoder) 
    self.layer.borderColor = UIColor.blueColor().CGColor 
    self.layer.borderWidth = 2 
    self.layer.cornerRadius = self.frame.size.width/2 

    } 
} 

class WBMainViewController: UIViewController { 

var timeControl = WBTimeController() 

var timer = NSTimer() 

@IBOutlet weak var timeDisplay: UILabel! 

//this doesn't work as expected ????? 
@IBOutlet weak var startButton: WBCircleButton! 


//******************************************** 
@IBAction func startTimer(sender: AnyObject) { 

    timeControl.startTimer() 

    startButton.setTitle("Stop", forState: UIControlState.Normal) 

    let aSelector: Selector = "updateTimerDisplay" 

    timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: aSelector, userInfo: nil, repeats: true) 

} 


//******************************************** 
func updateTimerDisplay() { 
    timeDisplay.text = timeControl.timeLabelText 
} 

//******************************************** 
override func viewDidLoad() { 
    super.viewDidLoad() 

} 

//******************************************** 
override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 

回答

3

我想你沒有驗證一些東西。我創建了一個Xcode單一視圖應用程序模板項目,並執行了以下操作(檢查每個步驟以查看缺少的內容)。

在項目導航:

創建一個新的UIViewController類文件,命名爲「WBMainViewController」,並設置該代碼是:

import UIKit 

class WBMainViewController: UIViewController { 

    @IBOutlet weak var startButton: WBCircleButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     startButton.setTitle("Stop", forState: UIControlState.Normal) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 

} 

在你的項目中創建一個新的UIButton類文件,命名爲 「WBCircleButton」,並設置在它下面的代碼:

import UIKit 

class WBCircleButton: UIButton { 

    required init(coder decoder: NSCoder) { 
     super.init(coder: decoder) 

     layer.borderColor = UIColor.blueColor().CGColor 
     layer.borderWidth = 2 
     layer.cornerRadius = self.frame.size.width/2 
    } 

} 

在Interface Builder中:

選擇您的UIViewController場景並將其類設置爲Identity Inspector中的「WBMainViewController」。

將UIButton添加到您的場景中,爲其設置自動佈局約束,並在Identity Inspector中將您的UIButton類設置爲「WBCircleButton」。

選擇您的ViewController場景並單擊「顯示助理編輯器」。一定要顯示您的ViewController代碼,並將您的startButton IBOutlet拖放到Interface Builder場景中的UIButton上。

啓動您的項目。

我可以在模擬器啓動我的項目後顯示在我的ViewController這個大按鈕:

enter image description here

+0

這偉大的工作。我在viewController中定義了自定義按鈕類,一旦它被放置在一個單獨的文件中,並且被附加,它就會顯示屬性。我沒有意識到,在viewController中定義按鈕類不是要走的路。 – 2014-09-01 14:55:40