加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift扩展示例

发布时间:2020-12-14 05:58:11 所属栏目:百科 来源:网络整理
导读:我最初想知道如何做这样的事情 UIColor.myCustomGreen 所以我可以定义我自己的颜色,并在我的应用程序中使用它们。 我之前已经研究了扩展名,我以为我可以用它来解决我的问题,但是我不记得如何设置扩展。在撰写本文时,Google搜索“Swift扩展”导致document
我最初想知道如何做这样的事情
UIColor.myCustomGreen

所以我可以定义我自己的颜色,并在我的应用程序中使用它们。

我之前已经研究了扩展名,我以为我可以用它来解决我的问题,但是我不记得如何设置扩展。在撰写本文时,Google搜索“Swift扩展”导致documentation,several长时间tutorials,并且相当无用的Stack Overflow question。

所以答案是在那里,但它需要一些挖掘通过文档和教程。我决定写这个问题和下面的答案,为Stack Overflow增加一些更好的搜索关键字,并提供一个快速回顾如何设置扩展。

具体我想知道:

>扩展位置在哪里(文件和命名约定)?
>什么是扩展语法?
>几个简单的常用例子是什么?

创建扩展名

添加一个新的swift文件,文件>新>文件…> iOS>来源> Swift文件,但你可以称呼他们想要什么。

一般的命名约定是将它称为TypeName NewFunctionality.swift。

示例1 – Double

双重转换

import Swift // or Foundation

extension Double {

    func celsiusToFahrenheit() -> Double {
        return self * 9 / 5 + 32
    }

    func fahrenheitToCelsius() -> Double {
        return (self - 32) * 5 / 9
    }
}

用法:

let boilingPointCelsius = 100.0
let boilingPointFarenheit = boilingPointCelsius.celsiusToFahrenheit()
print(boilingPointFarenheit) // 212.0

示例2 – String

字符串Shortcuts.swift

import Swift // or Foundation

extension String {

    func replace(target: String,withString: String) -> String {
        return self.replacingOccurrences(of: target,with: withString)
    }
}

用法:

let newString = "the old bike".replace(target: "old",withString: "new")
print(newString) // "the new bike"

Here是一些更常见的字符串扩展。

示例3 – UIColor

UIColor CustomColor.swift

import UIKit

extension UIColor {

    class var customGreen: UIColor {
        let darkGreen = 0x008110
        return UIColor.rgb(fromHex: darkGreen)
    }

    class func rgb(fromHex: Int) -> UIColor {

        let red =   CGFloat((fromHex & 0xFF0000) >> 16) / 0xFF
        let green = CGFloat((fromHex & 0x00FF00) >> 8) / 0xFF
        let blue =  CGFloat(fromHex & 0x0000FF) / 0xFF
        let alpha = CGFloat(1.0)

        return UIColor(red: red,green: green,blue: blue,alpha: alpha)
    }
}

另见here。

用法:

view.backgroundColor = UIColor.customGreen

笔记

>一旦定义了扩展名,就可以像应用程序中的内置函数一样在应用程序的任何位置使用它。
>如果您不确定函数或属性语法的外观,您可以选择一个类似的内置方法。例如,当我的选项点击UIColor.greenColor我看到声明是类func greenColor() – > UIColor。这给了我一个很好的线索,如何设置我的自定义方法。
> Apple Documentation for Extensions> Objective-C扩展名称为类别。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读