我正在尝试在点击按钮时添加另一个子视图。
使用storyboard创建第一个视图,按钮操作正常。 但是当我将新的viewcontroller视图添加为子视图并单击按钮时,应用程序在iPhone模拟器上与exc_bad_access崩溃。
这是代码:
override func viewDidLoad() {
super.viewDidLoad()
let datePick : UIDatePicker = UIDatePicker(frame: CGRectMake(0, 0, 218, 216))
datePick.backgroundColor = UIColor.whiteColor()
datePick.layer.borderColor = UIColor.blackColor().CGColor
datePick.layer.borderWidth = 5
let actionView : UIView = UIView(frame: CGRectMake(0, 216, datePick.frame.width, 50))
actionView.backgroundColor = UIColor.blackColor()
self.view.addSubview(datePick)
var cancelButton : UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
cancelButton.frame = CGRectMake(datePick.frame.width-80, 5, 60, 40)
cancelButton.setTitle("Cancel", forState: UIControlState.Normal)
cancelButton.backgroundColor = UIColor.redColor()
cancelButton.addTarget(self, action: "cancelPressed:", forControlEvents: UIControlEvents.TouchUpInside)
actionView.addSubview(cancelButton)
var doneButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
doneButton.frame = CGRectMake(20, 5, 60, 40)
doneButton.backgroundColor = UIColor.greenColor()
doneButton.setTitle("Done", forState: .Normal)
doneButton.addTarget(self, action: "buttonAction:",forControlEvents:UIControlEvents.TouchUpInside)
self.view.addSubview(actionView)
actionView.addSubview(doneButton)
// datePicker.frame = CGRectMake(0, 0, 218, 216);
// Do any additional setup after loading the view, typically from a nib.
}
func buttonAction(sender:UIButton!)
{
println("Button tapped")
}
func cancelPressed(sender: UIButton!) {
println("Cancel Clicked!!!")
}
从第一个viewcontroller的视图调用的IBAction方法是:
@IBAction func dateSelectClicked (sender:AnyObject){
var datePicker = DatePicker()
datePicker.view.frame = CGRectMake(0, self.view.frame.height, self.view.frame.width, self.view.frame.height)
let isfinished : Bool = true
self.view.addSubview(datePicker.view)
UIView.animateWithDuration(0.5, delay: 1.0 , options: UIViewAnimationOptions.CurveEaseInOut, animations: { datePicker.view.frame = CGRectMake(0, self.view.frame.height-266, self.view.frame.width, self.view.frame.height)}, completion: {(isfinished) in println("finished")})
}
答案 0 :(得分:0)
更改以下两行:
self.view.addSubview(actionView)
actionView.addSubview(doneButton)
为:
actionView.addSubview(doneButton)
self.view.addSubview(actionView)
答案 1 :(得分:0)
最后我发现了问题:
如有问题,DatePicker viewcontroller正在添加为:
var datePicker = DatePicker()
点击按钮。(func dateSelectClicked)
所以这是创建DatePicker实例的问题。
我们需要将其创建为方法外的方法:
Class firstViewController :UIViewController {
var datePicker = DatePicker()
}
并在方法self.datepicker
中用作属性