IOS8中swift 弹出框的显示

吴统威 on 编程语言 SWIFT | 2015-04-17 08:32:54.0

弹出框不管是在网页端,还是在手机APP端,都是常用的控件.在网页中实现个简单的弹出框只需要调用alert,在IOS中,也不是那么复杂,也是容易使用的.

我先用xcode6创建一个名为iOS8SwiftAlertViewTutorial,设置好相关的信息.

1.png

Storyboard中调整好视图显示方式

2.png

拖动一个按钮到主视图,设定其值为 "Show Alert"

3.png

按下Ctrl键,拖动按钮到代码中,加入点击事件

4.png


控制器代码中会出现IBAction方法

@IBAction func buttonTapped(sender: AnyObject) {
  
}

好的,现在整个代码完成了一大半了,就只缺弹出框的创建和显示了.现在我们在buttonTapped方法中加入以下代码

@IBAction func buttonTapped(sender: AnyObject) {
  
     let alertController = UIAlertController(title: "iOScreator", message:    "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)  
     alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))  
     self.presentViewController(alertController, animated: true, completion: nil)
     
}

ok,代码完成,我们通过UIAlertController来实现创建弹出框,且加入一个空的按钮事件,在通过呈现的方式显示弹出框,我们运行代码,显示如下

5.png