文章目录

  • 1、倒计时计时器
  • 2、`UIAlertController`提示框
  • 3、更换`APP`图标
  • 4、应用`3DTouch`
  • 5、最高分数(历史记录)
  • 6、角度/弧度转换扩展
  • 7、识别用户机型
  • 8、UITabBar弹性动画
  • 9、UIAlert短提示
  • 10、随机数扩展
  • 11、摇晃设备侦测

1、倒计时计时器

    var second = 0var minute = 0var hour = 0var time: Timer!func TimeLabel() -> String {if second == 60 {second = 0minute += 1}if minute == 60 {minute = 0hour += 1}return String(hour) + ":" + String(minute) + ":" + String(second)}func countDown() {second += 1<#UIlabel name#>.text = TimeLabel()}override func viewDidLoad() {super.viewDidLoad()// MARK: - Timertime = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer) inself.countDown()})}

这是一个计时器的代码片段,把这段代码复制到Xcode中。首先你要把storyboard中的一个UILabel用插座变量插到代码里,再在UILabel name占位符中输入你的UILabel名。运行项目,UILabel会像计时器一样,0:0:1…0:0:2…0:0:3…,但是这个方法有缺陷。它在时、分、秒为个位数时,不能有0占位(例如只能显示0:0:1却不能显示00:00:01)。

2、UIAlertController提示框

func alertUser(title: String, subtitle: String) {let alert = UIAlertController(title: title,message: subtitle,preferredStyle: .alert)let action = UIAlertAction(title: "OK",style: .default)alert.addAction(action)self.present(alert, animated: true)
}

把这个函数定义到项目中,然后调用此函数,标题为title,副标题为subtitle。这是最基本的警告框。

3、更换APP图标

Info.plist中配置:

<key>CFBundleIcons</key><dict><key>CFBundlePrimaryIcon</key><dict><key>CFBundleIconFiles</key><array><string></string></array></dict><key>CFBundleAlternateIcons</key><dict><key>icon1</key><dict><key>CFBundleIconFiles</key><array><string>icon1</string></array><key>UIPrerenderedIcon</key><false/></dict><key>icon2</key><dict><key>CFBundleIconFiles</key><array><string>icon2</string></array><key>UIPrerenderedIcon</key><false/></dict></dict></dict>

代码里配置:

func changeAppIcon(withName iconName: String?) {var iconName = iconNameif !UIApplication.shared.supportsAlternateIcons { return }if (iconName == "") { iconName = nil }UIApplication.shared.setAlternateIconName(iconName, completionHandler: { error inif error != nil {if let anError = error {print("更换app图标发生错误了: \(anError)")}}})
}

这两段代码必须配合使用。首先以源代码的方式打开Info.plist,把第一段XML粘贴进去。之后把第二段函数粘贴到代码中。在需要更换APP图标的地方调用这段代码。记住,要在项目里添加多个应用图标!

4、应用3DTouch

        let showFirst = UIApplicationShortcutItem(type: "名字", localizedTitle: "标题", localizedSubtitle: "副标题", icon: UIApplicationShortcutIcon(type: .图标), userInfo: nil)let showSecond = UIApplicationShortcutItem(type: "<#name#>", localizedTitle: "<#title#>", localizedSubtitle: "<#subtitle#>", icon: UIApplicationShortcutIcon(type: .add), userInfo: nil)let showThird = UIApplicationShortcutItem(type: "<#name#>", localizedTitle: "<#title#>", localizedSubtitle: "<#subtitle#>", icon: UIApplicationShortcutIcon(type: .search), userInfo: nil)let shortCutItems = [showFirst, showSecond, showThird]application.shortcutItems = shortCutItems;func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler compelecationHandler: (Bool) -> Void){if shortcutItem.type == "<#name#>" {//进入第1个界面的代码} else if shortcutItem.type == "<#name#>" {//进入第2个界面的代码} else if shortcutItem.type == "<#name#>" {//进入第3个界面的代码}}

把这段代码覆盖到AppDelegate中。记得把需要填充的占位符填上。我在第一个let里已经注释了。在下面的if else if语句中,用代码跳转到需要的窗口。

5、最高分数(历史记录)

func biggestScore() -> Int { // getreturn UserDefaults.standard.integer(forKey: "最高分数关键词")
}func setBiggestScore(_ number: Int) { // setUserDefaults.standard.set(number, forKey: "最高分数关键词")UserDefaults.standard.synchronize()
}

这里有两个函数。第一个函数是获取硬盘中的变量的,第二个函数是设置变量的。这些代码名字与参数可以根据自己的风格更改。记得把最高分数关键词填上自己的变量名字,以便获取。

6、角度/弧度转换扩展

extension Double {func radianToDegree() -> Double {return (.pi * self) / 180}func degreeToRadian() -> Double {return self / 180 * .pi}
}

这段代码是一个Double的扩展。有些程序里会需要在角度与弧度内互相转换,那么,直接把这个扩展放到代码里,之后直接调用即可。例如要把3.2角度换成弧度,直接3.2.degreeToRadian(),如果要把弧度换成角度,调用radianToDegree()即可。

7、识别用户机型

public extension UIDevice {var modelName: String {var systemInfo = utsname()uname(&systemInfo)let machineMirror = Mirror(reflecting: systemInfo.machine)let identifier = machineMirror.children.reduce("") { identifier, element inguard let value = element.value as? Int8, value != 0 else { return identifier }return identifier + String(UnicodeScalar(UInt8(value)))}switch identifier {case "iPod5,1": return "iPod Touch 5"case "iPod7,1": return "iPod Touch 6"case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"case "iPhone4,1":  return "iPhone 4s"case "iPhone5,1", "iPhone5,2": return "iPhone 5"case "iPhone5,3", "iPhone5,4": return "iPhone 5c"case "iPhone6,1", "iPhone6,2": return "iPhone 5s"case "iPhone7,2": return "iPhone 6"case "iPhone7,1": return "iPhone 6 Plus"case "iPhone8,1": return "iPhone 6s"case "iPhone8,2": return "iPhone 6s Plus"case "iPhone8,4": return "iPhone SE"case "iPhone9,1": return "iPhone 7"case "iPhone9,2": return "iPhone 7 Plus"case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2"case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"case "iPad5,3", "iPad5,4": return "iPad Air 2"case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"case "iPad5,1", "iPad5,2": return "iPad Mini 4"case "iPad6,7", "iPad6,8": return "iPad Pro"case "AppleTV5,3": return "Apple TV"case "i386", "x86_64": return "Simulator"default: return identifier}}
/*// Use this declaration to output device information.let modelName = UIDevice.current.modelName*/
}

这是个对UIDevice进行的扩展,稍微有些长。这个扩展可以辨别用户当前使用的机型。
如果你想知道用户在用什么手机,使用UIDevice.current.modelName即可获取信息。

8、UITabBar弹性动画

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {for (k,v) in (tabBar.items?.enumerated())! {if v == item {// print(k)animationWithIndex(index: k)}}
}func animationWithIndex(index: Int) {var tabbarbuttonArray: [Any] = []for tabBarBtn in self.tabBar.subviews {if tabBarBtn.isKind(of: NSClassFromString("UITabBarButton")!) {tabbarbuttonArray.append(tabBarBtn)}}let pulse = CABasicAnimation(keyPath: "transform.scale")pulse.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)pulse.duration = 0.08pulse.repeatCount = 1pulse.autoreverses = truepulse.fromValue = 0.7pulse.toValue = 1.3let tabBarLayer = (tabbarbuttonArray[index] as AnyObject).layertabBarLayer?.add(pulse, forKey: nil)
}

我们开发APPUITabBar几乎是必不可少的。然而系统给的默认TabBar切换生硬,很难看。这段代码可以实现每一个UITabBarItem在点击时,做一个小小的弹性动画,很简约美观。想要使用这段代码,先在Storyboard中新建一个UITabBarViewController,再为这个UITabBarViewController创建一个.swift文件(继承UITabBarViewController),在新建的文件中覆盖此段代码,即可生效。

9、UIAlert短提示

func showLittleAlert(title: String, message: String, seconds: TimeInterval) {let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)self.present(alertController, animated: true, completion: nil)DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds) {self.presentedViewController?.dismiss(animated: false, completion: nil)}
}

这段代码跟前面那个(第二个)有所不同。这个短提示其实是没有OK键的那种,显示到屏幕上,等几秒种,自动消失。想要使用就把这个函数放到项目代码里,之后调用。title:是主标题,subtitle是副标题,seconds是一个TimeInterval,是提示框在屏幕上停留的时间。

10、随机数扩展

extension Int {var randomNumber: Int {if self > 0 {return Int(arc4random_uniform(UInt32(self)))} else if self < 0 {return -Int(arc4random_uniform(UInt32(abs(self))))} else { return 0 }}
}

这是一个关于Int的扩展。当你想要一个0及以上的随机整数时,直接调用randomNumber这个变量。

11、摇晃设备侦测

override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {print("开始摇晃")
}// 摇晃结束
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {print("摇晃结束")
}// 摇晃被意外终止
override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent) {print("摇晃被意外终止")
}

摇晃手机也是一种常用的交互手段(比如微信摇一摇功能)。iOS SDK中已经将shake事件方便地融合进去了,就像触发touch事件一样简单,发生摇晃事件后程序会自动执行。在需要的地方填上自己的动作即可。

【Swift UIKit】11个值得收藏的代码片段相关推荐

  1. python 情书_用Python做一个520表白神器,值得收藏(示例代码)

    本文最后给出了打包好的软件,无需安装Python环境和各种依赖,直接下载软件,解压后,双击exe文件即可使用. 先来看一下具体的效果. 运行程序. 点击「选择图片」 选择JPG/JPGE/PNG三种中 ...

  2. [纯代码] Swift+UIKit · 搭建第一个iOS APP项目

    本文目录 前言 创建一个纯代码编辑的Swift + UIKit项目 创建一个Swift + UIKit项目 让它变成纯代码编辑的 让你的APP打开指定的ViewController 创建一个窗口 编辑 ...

  3. 学习必备的50条非常有趣且实用的Python一行代码,值得收藏

    前言 学习必备的50条非常有趣且实用的Python一行代码,值得收藏! 让我们愉快地开始吧~编程学习资料免费点击 开发工具 Python版本: 3.6.4 相关模块: 环境搭建 安装Python并添加 ...

  4. 值得收藏的北京移动短信代码

    值得收藏的北京移动短信代码 发送CXBX到10086,查询当月套餐剩余短信条数. 发送CXGFX到10086,查询当月飞信GPRS套餐剩余流量. 发送CXGTC到10086,查询当月GPRS套餐剩余流 ...

  5. pythonic 代码_15个Pythonic的代码示例(值得收藏)

    Python由于语言的简洁性,让我们以人类思考的方式来写代码,新手更容易上手,老鸟更爱不释手. 要写出 Pythonic(优雅的.地道的.整洁的)代码,还要平时多观察那些大牛代码,Github 上有很 ...

  6. 前端:收集15个非常实用的JS代码,值得收藏

    CSDN话题挑战赛第2期 参赛话题:学习笔记 目录 1.随机生成字符串 2.实现字符串的翻转 3.删除数组中重复元素 4.RGB到十六进制转换机制 5.打乱一个数组,重新组合 6.获取两个日期的时间间 ...

  7. 值得收藏的一些网页代码(asp,js,hml)

    值得收藏的一些网页代码(asp,js,hml) 编程开发  谌忠辉 2004年3月22日 ------------------------------------------------------- ...

  8. pythonfor循环语句例子_值得收藏!16段代码入门Python循环语句

    原标题:值得收藏!16段代码入门Python循环语句 导读:本文重点讲述for语句和while语句.for语句属于遍历循环,while语句属于当型循环.除了两个循环语句外,还介绍了break.cont ...

  9. 分享6 个值得收藏的 Python 代码

    1.类有两个方法,一个是 new,一个是 init,有什么区别,哪个会先执行呢? 1 class test(object):​​​ def __init__(self):​​​ print(" ...

最新文章

  1. MYSQL体系结构-来自期刊
  2. 元素节点、属性节点、文本节点 的节点属性
  3. RocketMQ--生产者与消费者的简单示例
  4. 基于概率统计分析的应用流特征分析
  5. 【Java/JFrame/多线程】小球碰到边缘的回弹效果
  6. windows下备份mysql 数据库
  7. MongoDB搭建和简单操作(windows环境)
  8. python代理池_用Python搭建一个简单的代理池
  9. 恢复IE8自带的源代码查看器
  10. 面试鹅厂,我三面被虐的体无完肤……
  11. 为什么Spark能成为最火的大数据计算引擎?它是怎样工作的?
  12. 字符串转整数,不使用任何C语言库函数
  13. 35行代码利用python生成字符画,非常适合初学者练习,附源码!
  14. 常问 3: 谈谈MySQL共享锁与排他锁
  15. url_regex和urlpath _regex区别
  16. Codeforces 120F Spiders
  17. python 打包exe 运行dll load failed_Python ImportError: DLL load failed: %1 不是有效的 Win32 应用程序。...
  18. 修改windows cmd f2快捷_解放你的右手,实测12个超好用的自带快捷键
  19. Pytorch+opencv 手势识别
  20. 深入研究java.lang.Class类

热门文章

  1. html text-indent,css之text-indent
  2. 目前流行的装修风格_目前装修流行的主要八大风格
  3. 【2021】某红书笔记点赞数收藏数评论数转发接口
  4. VOT tooklit 数据集 安装配置出错:Tracker has not passed the TraX support test.
  5. 化学物质零排放ZDHC
  6. 荒野白牡丹都有啥功效,白牡丹茶对人体的功效与作用
  7. 什么是不设限的未来?
  8. vsnprintf 变参
  9. graylog3.3部署及配置
  10. 我们都羡慕李白的洒脱,其实高适才是我们真实的人生