2014-08-31 59 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