注:如果要实现某个控件的委托协议,需要将当前控件指向当前视图在弹出的列表中选择Delegate
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIWebViewDelegate {
//, UIAlertViewDelegate, UIActionSheetDelegate //使用alertcontroller实现alert与actionsheet @ 对应的委托协议就不需要了
//Outlet 输出口
@IBOutlet weak var label: UILabel!
@IBOutlet weak var leftSwich: UISwitch!
@IBOutlet weak var rightSwitch: UISwitch!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var txtField: UITextField!//需要指向 故事板的 View Controller
@IBOutlet weak var textView: UITextView!//需要指向 故事板的 View Controller
@IBOutlet weak var webView: UIWebView!//需要指向 故事板的 View Controller
@IBOutlet weak var imgView: UIImageView!
@IBOutlet weak var myActivityIndecatorView: UIActivityIndicatorView!//loading...相当于网页中的gif菊花
@IBOutlet weak var myprogressView: UIProgressView!
var myTimer = Timer()//定时器
//Button 按钮
@IBAction func onclick(_ sender: UIButton) {
//根据button的tag判断要执行的操作
switch sender.tag {
case 1:
self.textout(text: "Button Swift Code")
case 2:
self.textout(text: "Button PHP Code")
case 5:
self.textout(text: "Webview Load Html")
self.imgView.isHidden = true//隐藏图片
//得到index.html物理路径,根路径
let htmlPash = Bundle.main.path(forResource: "index", ofType: "html")
//得到lao.html的目录物理路劲
let bundleURL = NSURL.fileURL(withPath: Bundle.main.bundlePath)
//读取本地HTML文件为字符串 尾部有throws需要处理异常
let htmlString = try? NSString.init(contentsOfFile: htmlPash!, encoding: String.Encoding.utf8.rawValue)
//loadHTMLString 为加载本地html字符串
self.webView.loadHTMLString(htmlString as! String, baseURL: bundleURL)
case 6:
self.textout(text: "Webview Load Data")
self.imgView.isHidden = true//隐藏图片
//得到data.html物理路径,根路径
let htmlPash = Bundle.main.path(forResource: "data", ofType: "html")
//得到lao.html的目录物理路劲
let bundleURL = NSURL.fileURL(withPath: Bundle.main.bundlePath)
//读取本地HTML到Data里
let htmlData = try? NSData.init(contentsOfFile: htmlPash!, options: NSData.ReadingOptions.uncached)
//load为 loadData方式加载(二进制)数据
self.webView.load(htmlData as! Data, mimeType: "text/html", textEncodingName: "UTF-8", baseURL: bundleURL)
case 7:
self.textout(text: "Webview Load Request")
self.imgView.isHidden = true//隐藏图片
//设置访问资源 - 百度搜索
let url = URL(string: "https://www.baidu.com/")//只能https,http当前版本做了限制
//建立网络请求
let request = URLRequest(url: url!)
//加载网络请求
webView.loadRequest(request)
case 10:
self.textout(text: "imageView This is my son !")
self.imgView.isHidden = false//显示图片
case 11:
/*let alertView = UIAlertView()//alert弹框,系统会提示 ios9.0 UIAlertView 会被 UIAlertController 代替
alertView.title = "System Message"
alertView.message = "This is test alert !"
alertView.addButton(withTitle: "no")
alertView.addButton(withTitle: "yes")
alertView.cancelButtonIndex = 0//设置取消按钮的索引
alertView.delegate = self//委托协议
alertView.show()*/
//UIAlertController 方式实现 alert 且无需委托协议 @ UIAlertControllerStyle.alert
let alertcontroller = UIAlertController(title: "System Message", message: "This is test alert !", preferredStyle: UIAlertControllerStyle.alert)//实例化UIAlertController & 调用构造方法
alertcontroller.addAction(UIAlertAction(title: "no", style: UIAlertActionStyle.cancel, handler: { (alert) in
self.textout(text: "Alert Click on no !")//添加cancel按钮
}))
alertcontroller.addAction(UIAlertAction(title: "yes", style: UIAlertActionStyle.default, handler: { (alert) in
self.textout(text: "Alert Click on yes !")//添加default按钮
}))
self.present(alertcontroller, animated: true, completion: {
self.textout(text: "Alert show")//提出 UIAlertController
})
case 12:
/*let actionSheet = UIActionSheet(title: "Test ActionSheet", delegate: self, cancelButtonTitle: "cancel", destructiveButtonTitle: "destructive!!!")//ActionSheet表操作,系统会提示 ios9.0 UIActionSheet 会被 UIAlertController 代替
actionSheet.actionSheetStyle = UIActionSheetStyle.default//设置 UIActionSheet 的样式
actionSheet.cancelButtonIndex = 1//设置取消按钮的索引
actionSheet.destructiveButtonIndex = 0//设置destructive的索引值
actionSheet.addButton(withTitle: "Button one")//添加其他按钮的标题
actionSheet.addButton(withTitle: "Button two")//添加其他按钮的标题
actionSheet.buttonTitle(at: 1)//设置按钮标题的索引
actionSheet.show(in: self.view)//显示到 self.view 上*/
//UIAlertController 方式实现 ActionSheet 且无需委托协议 @ UIAlertControllerStyle.actionSheet
let alertcontroller = UIAlertController(title: "Test ActionSheet title", message: "Test ActionSheet message", preferredStyle: UIAlertControllerStyle.actionSheet)//实例化UIAlertController & 调用构造方法
alertcontroller.addAction(UIAlertAction(title: "destructive!!!", style: UIAlertActionStyle.destructive, handler: { (alert) in
self.textout(text: "ActionSheet Click on destructive !")//添加destructive按钮
}))
alertcontroller.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.cancel, handler: { (alert) in
self.textout(text: "ActionSheet Click on cancel !")//添加cancel按钮
}))
alertcontroller.addAction(UIAlertAction(title: "button one", style: UIAlertActionStyle.default, handler: { (alert) in
self.textout(text: "ActionSheet Click on button one !")//添加default按钮
}))
alertcontroller.addAction(UIAlertAction(title: "button two", style: UIAlertActionStyle.default, handler: { (alert) in
self.textout(text: "ActionSheet Click on button two !")//添加default按钮
}))
self.present(alertcontroller, animated: true, completion: {
self.textout(text: "ActionSheet show")//提出 UIAlertController
})
default: break
}
}
//Switch 开关
@IBAction func switchValueChanged(_ sender: UISwitch) {
let switchIsOn: Bool = sender.isOn//当前swicth状态
leftSwich.setOn(switchIsOn, animated: true)//设置swicth状态
rightSwitch.setOn(switchIsOn, animated: true)//设置swicth状态
self.switchLabel(switchis: switchIsOn)//显示文字到label
self.slider.isHidden = !switchIsOn//隐藏slider
}
//Slider 滑块
@IBAction func sliderValueChanged(_ sender: Any) {
//强制转换为UISlider @ 其实不用,在连接的时候给定类型为 UISlider就可以
let sliderObj = sender as! UISlider
let newText = String(format: "%.0f", sliderObj.value)//String方法,截取小数 ,sliderObj.value当前slider的值
self.textout(text: "Slider Number: \(newText)")
}
//segmented 分段
@IBAction func touchValueChanged(_ sender: Any) {
let touchObj = sender as! UISegmentedControl//强制转换为UISlider @ 其实用,在连接的时候给定类型为 UISegmentedControl就可以
let selectedSegmentIndex = touchObj.selectedSegmentIndex//被点击segment的索引
let selectdSegmentText = touchObj.titleForSegment(at: touchObj.selectedSegmentIndex) ?? "Red"//被点击segment的text
switch selectedSegmentIndex {
case 0:
touchObj.tintColor = UIColor.red//设置颜色而已
label.textColor = UIColor.red//label颜色
case 1:
touchObj.tintColor = UIColor.blue
label.textColor = UIColor.blue
case 2:
touchObj.tintColor = UIColor.black
label.textColor = UIColor.black
case 3:
touchObj.tintColor = UIColor.green
label.textColor = UIColor.green
case 4:
touchObj.tintColor = UIColor.yellow
label.textColor = UIColor.yellow
default: break
}
self.textout(text: "Segmented Color: \(selectdSegmentText)")
}
//navigation 导航栏 button item
@IBAction func navigationitem(_ sender: UIBarButtonItem) {
switch sender.tag {
case 5:
self.textout(text: "Navigation save")
case 6:
self.textout(text: "Navigation add")
default: break
}
}
//toolbar 工具栏的 button item
@IBAction func onclickBarButtonitem(_ sender: UIBarButtonItem) {
switch sender.tag {
case 1:
self.textout(text: "Toolbar mysql")
case 2:
self.textout(text: "Toolbar mongdb")
case 3:
self.textout(text: "Toolbar oracle")
case 4:
self.textout(text: "Toolbar sqlserver")
default: break
}
}
//textField 单行文本输入框 [以下为协议委托的方法实现...]
//开始输入时
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.textout(text: "TextField BeginEditing")
return true
}
//结束输入时
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
self.textout(text: "TextField EndEditing")
}
//按回车时
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.textout(text: "TextField Return")
//textField.resignFirstResponder()//放弃第一响应者的方式,关闭键盘
textView.becomeFirstResponder()//让textView 成为第一响应者
return true
}
//textView 多行文本(非控件)[以下为协议委托的方法实现...]
//开时输入时
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
self.textout(text: "TextView BeginEditing")
return true
}
//当文本改变时
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
self.textout(text: "TextView Change")
if text == "\n" {
textView.resignFirstResponder()//放弃第一响应者的方式,关闭键盘
}
return true
}
//webView 加载http [以下为协议委托的方法实现...]
//准备加载
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
self.textout(text: "WebView shouldStartLoadWith")
self.myActivityIndecatorView.startAnimating()//indicator 开转
self.myprogressView.progress = 0.3//准备加载时,progress 值为0.3
return true
}
//开始加载
func webViewDidStartLoad(_ webView: UIWebView) {
self.textout(text: "WebView webViewDidStartLoad")
self.myTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(getter: UIPreviewAction.handler), userInfo: nil, repeats: true)//定时器调用,每隔0.05秒点用一次handler方法,repeats: true为是否重复调用
}
//加载完成
func webViewDidFinishLoad(_ webView: UIWebView) {
self.textout(text: "WebView webViewDidFinishLoad")
self.myActivityIndecatorView.stopAnimating()//indicator 停转
}
//加载错误
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
self.textout(text: "WebView didFailLoadWithError")
if self.myActivityIndecatorView.isAnimating {//如果在转
self.myActivityIndecatorView.stopAnimating()//停转
}
}
//alertView 获取按钮索引进行操作 [以下为协议委托的方法实现...] @ 已使用alertcontroller实现
/*func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
//系统会提示 ios9.0 UIAlertView 会被 UIAlertController 代替
if buttonIndex == 0 {
self.textout(text: "Click on no !")
}else if buttonIndex == 1 {
self.textout(text: "Click on yes !")
}
}*/
//actionsheet 表操作 [以下为协议委托的方法实现...] @ 已使用alertcontroller实现
/*func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
//系统会提示 ios9.0 UIActionSheet 会被 UIAlertController 代替
if buttonIndex == 0 {
self.textout(text: "Click on destructive !")
}else if buttonIndex == 1 {
self.textout(text: "Click on cancel !")
}else if buttonIndex == 2 {
self.textout(text: "Click on button one !")
}else if buttonIndex == 3 {
self.textout(text: "Click on button two !")
}
}*/
//viewWillAppear 中可注册事件通知
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//NSNotification.Name.UIKeyboardWillShow 键盘打开通知
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardDidShow(notification:)),name: NSNotification.Name.UIKeyboardWillShow, object: nil)
//NSNotification.Name.UIKeyboardWillHide 键盘关闭通知
NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(notification:)),name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//viewWillDisappear 中可注销事件通知
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//注销键盘打开通知
NotificationCenter.default.removeObserver(self,name: NSNotification.Name.UIKeyboardWillShow, object: nil)
//注销键盘关闭通知
NotificationCenter.default.removeObserver(self,name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
//My Func
//显示label文本
func textout(text: String) {
label.text = "【 \(text) 】"
}
//switch开关显示文修的
func switchLabel(switchis: Bool) {
if switchis {
self.textout(text: "SwitchLabel Full Open")
}else{
self.textout(text: "SwitchLabel Full Close")
}
}
//键盘的通知 打开和关闭 日志
func keyBoardDidShow(notification: Notification){
print("键盘打开")
}
func keyBoardWillHide(notification: Notification){
print("键盘关闭")
}
//progress 使用 timer 模拟进度显示
func handler(){
self.myprogressView.progress = self.myprogressView.progress + 0.02
if self.myprogressView.progress == 1 {
self.myTimer.invalidate()//关闭Timer
//self.myTimer = nil //据说说可以清内存,但会报错 @ 未解决
}
}
//==================================================================================
//System Func
override func viewDidLoad() {
super.viewDidLoad()
//使用swift创建imageViews 加载一张图片
/*let imageViews = UIImageView(image:UIImage(named:"ZSY"))
imageViews.frame = CGRect(x:60, y:391, width:297, height:312)
self.imageView = imageViews//赋值到类属性
self.view.addSubview(imageViews)*/
self.imgView.image = UIImage(named: "cjt")//加载图片
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}