我尝试初始化自定义UIButton类,但我做错了,不知道如何实现它。我构建了一个自定义UIButton类并在IBOutlet中初始化它。按钮工作正常但没有显示我设置的属性。
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.
}
}
答案 0 :(得分: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中显示这个大按钮: