最新消息: USBMI致力于为网友们分享Windows、安卓、IOS等主流手机系统相关的资讯以及评测、同时提供相关教程、应用、软件下载等服务。

【SwiftUIKit】11个值得收藏的代码片段

IT圈 admin 2浏览 0评论

【Swift UIKit】11个值得收藏的代码片段

文章目录

    • 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、倒计时计时器
    • 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事件一样简单,发生摇晃事件后程序会自动执行。在需要的地方填上自己的动作即可。

发布评论

评论列表 (0)

  1. 暂无评论