首页 文章 精选 留言 我的

精选列表

搜索[ios],共10000篇文章
优秀的个人博客,低调大师

iOS - Swift Struct 结构体

1、Struct 的创建 1.1 基本定义 结构体的定义 // 定义结构体数据类型 struct BookInfo { // 每个属性变量都必须初始化 var ID:Int = 0 var Name:String = "Default" var Author:String = "Default" var RootType:String = "Default" } 结构体的使用 // 定义结构体变量 let book = BookInfo() // 结构体类型变量值的调用 print("\(book.ID), \(book.Name), \(book.Author), \(book.RootType)") 1.2 含方法的定义 结构体的定义 // 定义结构体数据类型 struct markStruct { var mark1:Int var mark2:Int var mark3:Int // 初始化方法 init(mark1:Int, mark2:Int, mark3:Int) { // 每个属性变量都必须初始化 self.mark1 = mark1 self.mark2 = mark2 self.mark3 = mark3 } // 方法定义 func sum(a:Int) -> Int { return (self.mark1 + self.mark2 + self.mark3) * a } } 结构体的使用 // 定义结构体变量 let mark = markStruct(mark1: 11, mark2: 22, mark3: 33) // 结构体类型变量值的调用 print("\(mark.mark1), \(mark.mark2), \(mark.mark3)") // 结构体类型方法的调用 print(mark.sum(2))

优秀的个人博客,低调大师

iOS - Swift NSEnumerator 迭代器

前言 public class NSEnumerator : NSObject, NSFastEnumeration 1、迭代器 let arr:NSArray = ["bei", "jing", "huan", "ying", "nin"] let dic:NSDictionary = ["key1":"value1", "key2":"value2", "key3":"value3"] // 创建数组 正序 迭代器 let arrEnumer1:NSEnumerator = arr.objectEnumerator() // 创建数组 反序 迭代器 let arrEnumer2:NSEnumerator = arr.reverseObjectEnumerator() // 创建字典 key 迭代器 let dicKeyEnumer:NSEnumerator = dic.keyEnumerator() // 创建字典 对象 迭代器 let dicObjEnumer:NSEnumerator = dic.objectEnumerator() // 获取迭代器中下一个对象 var obj: AnyObject? = arrEnumer1.nextObject() obj = arrEnumer1.nextObject() // 获取迭代器中所有对象 let array = arrEnumer2.allObjects 2、数组用迭代器遍历 let arr:NSArray = ["bei", "jing", "huan", "ying", "ni"] let enu1:NSEnumerator = arr.objectEnumerator() let enu2:NSEnumerator = arr.reverseObjectEnumerator() // AnyObject 后不要加 ?,否则会导致一直循环 while let obj:AnyObject = enu1.nextObject() { print(obj) } // AnyObject 后不要加 ?,否则会导致一直循环 while let obj:AnyObject = enu2.nextObject() { print(obj) } 3、集合用迭代器遍历 let nsSet:NSSet = [2, 4, 6, 8] let enu:NSEnumerator = nsSet.objectEnumerator() // AnyObject 后不要加 ?,否则会导致一直循环 while let obj:AnyObject = enu.nextObject() { print(obj) } 4、字典用迭代器遍历 let nsDic:NSDictionary = NSDictionary(dictionary: ["key1":1, "key2":2, "key3":3, "key4":4]) // key 迭代器 let keyEnu:NSEnumerator = nsDic.keyEnumerator() while let key:AnyObject = keyEnu.nextObject() { print(nsDic.objectForKey(key)) } // 对象迭代器 let objEnu:NSEnumerator = nsDic.objectEnumerator() while let obj:AnyObject = objEnu.nextObject() { print(obj) }

优秀的个人博客,低调大师

iOS - Swift NSFileManage 文件管理

前言 public class NSFileManager : NSObject public class NSFileHandle : NSObject, NSSecureCoding NSFileManager 是 Foundation 框架中用来管理和操作文件、目录等文件系统相关联内容的类。 1、路径操作 let nfManager = NSFileManager.defaultManager() let folderUrl:NSURL = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop/testFolder"))! let filerUrl:NSURL = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop/testFile.txt"))! let srcUrl:NSURL = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop/testFile.txt"))! let dstUrl:NSURL = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop/testFolder/testFile.txt"))! // 创建文件夹 /* public func createDirectoryAtPath(path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [String : AnyObject]?) throws path:文件夹路径 createIntermediates:是否连同上一级路径一起创建,NO 并且上一级文件路径不存在时会创建失败。 attributes:文件夹属性,nil 系统默认属性 */ try! nfManager.createDirectoryAtPath(folderUrl.path!, withIntermediateDirectories: true, attributes: nil) // 创建文件 /* func createFileAtPath(path: String, contents data: NSData?, attributes attr: [NSObject : AnyObject]?) -> Bool path:文件路径 data:文件内容,nil 空 attr:文件属性,nil 系统默认属性 Bool:文件创建成功时返回值为 true */ let bl1:Bool = nfManager.createFileAtPath(filerUrl.path!, contents: nil, attributes: nil) // 拷贝文件 /* 如果 dstUrl 路径文件已存在,该方法会终止拷贝,并返回 false。 如果 srcUrl 的最后一部分是符号链接,那么只有链接会被拷贝到新路径。 */ try! nfManager.copyItemAtPath(srcUrl.path!, toPath: dstUrl.path!) // 删除文件 /* 删除成功或者 url 为 nil 时返回 true,如果发生错误返回 false。如果使用 delegate 终止了删除文件的操作, 则返回 true,如果使用 delegate 终止了删除目录的操作,则返回 false。 */ try! nfManager.removeItemAtPath(dstUrl.path!) // 移动文件 /* 如果 dstUrl 路径文件已存在,该方法会终止移动,并返回 false。如果 srcUrl 的最后一部分是符号链接, 那么只有链接会被移动到新路径。链接所指向的内容仍然保持在现有的位置。 */ try! nfManager.moveItemAtPath(srcUrl.path!, toPath: dstUrl.path!) // 查找满足指定条件的路径 // 返回其 URL。该方法不但可以获得标准系统目录,还可以用来创建临时路径。 let url1:NSURL = try! nfManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) // 返回所有满足条件的路径列表 let urlObjs:[NSURL] = nfManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let url2:NSURL = urlObjs[0] // 查询指定路径下的所有子路径 let urls1:[String]? = nfManager.subpathsAtPath(url1.path!) let urls2:[String] = try! nfManager.subpathsOfDirectoryAtPath(url1.path!) // 浅遍历 // 返回指定目录下的文件、子目录及符号链接的列表 let contentsDir1:[String] = try! nfManager.contentsOfDirectoryAtPath(url1.path!) // 返回文件全路径 /* public func contentsOfDirectoryAtURL(url: NSURL, includingPropertiesForKeys keys: [String]?, options mask: NSDirectoryEnumerationOptions) throws -> [NSURL] 返回指定目录下的文件、子目录及符号链接的列表,返回的是文件全路径。 url:要进行搜索的目录路径,该路径不能为指向目标目录的符号链接,如果是可以使用 URLByResolvingSymlinksInPath 进行转换。 keys:用来传入进行搜索的一些特定条件,包括创建时间,修改时间等。 mask:SkipsHiddenFiles:表示不遍历隐藏文件, SkipsSubdirectoryDescendants:表示不递归到子目录内部, SkipsPackageDescendants:表示不递归到包内部。 */ let contentsDir2:[NSURL] = try! nfManager.contentsOfDirectoryAtURL(url1, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles) // 深遍历 // 返回指定目录下的所有文件及其子目录下的所有元素路径 let enumeratorDir1:NSDirectoryEnumerator = nfManager.enumeratorAtPath(url1.path!)! // 返回文件全路径 /* func enumeratorAtURL(url: NSURL, includingPropertiesForKeys keys: [AnyObject]?, options mask: NSDirectoryEnumerationOptions, errorHandler handler: ((NSURL!, NSError!) -> Bool)?) -> NSDirectoryEnumerator? 返回指定目录下的所有文件及其子目录下的所有元素路径,返回的是文件全路径。 url:要进行搜索的目录路径,该路径不能为指向目标目录的符号链接,如果是可以使用 URLByResolvingSymlinksInPath 进行转换。 keys:用来传入进行搜索的一些特定条件,包括创建时间,修改时间等。 mask:SkipsHiddenFiles:表示不遍历隐藏文件, SkipsSubdirectoryDescendants:表示不递归到子目录内部, SkipsPackageDescendants:表示不递归到包内部。 */ let enumeratorDir2:NSDirectoryEnumerator = nfManager.enumeratorAtURL(url1, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles, errorHandler: nil)! // 枚举遍历深层遍历 let dEnu:NSDirectoryEnumerator? = nfManager.enumeratorAtPath(url1.path!) while let obj:AnyObject? = dEnu?.nextObject() { print(obj) } // 显示路径的本地化名称 /* 如果指定的文件或目录不存在,会返回 path 本身。 */ let displayName:String = nfManager.displayNameAtPath(url1.path!) // 获取指定路径的各种属性 let attributes:[String:AnyObject] = try! nfManager.attributesOfItemAtPath(url1.path!) // 获取指定路径文件的内容数据 /* 如果指定路径为目录或发生错误,返回 nil。 */ let data:NSData? = nfManager.contentsAtPath(url1.path!.stringByAppendingString("/test.txt")) // 获取当前路径 let currentPath:String = nfManager.currentDirectoryPath // 更改当前路径 /* /Users/JHQ0228/Desktop/Debug */ let bl6:Bool = nfManager.changeCurrentDirectoryPath(NSHomeDirectory().stringByAppendingString("/Desktop/Debug")) // 获取临时工作路径 /* 获取系统中可以用来创建临时文件的目录路径名,一定要在完成任务之后将在其中创建的文件删除。 */ let tempPath:NSString = NSTemporaryDirectory() // 获取用户主路径(沙盒路径) let homePath:NSString = NSHomeDirectory() // 获取指定用户的主路径 /* NSUserName(); 获取当前用户的登录名。NSFullUserName(); 获取当前用户完整用户名 */ let userHomePath:String? = NSHomeDirectoryForUser(NSUserName()) // 获取用户 Documents 路径 let documentPath:NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] // 获取 app 包路径 let bundlePath = NSBundle.mainBundle().bundlePath // 创建一个新路径 try! nfManager.createDirectoryAtPath(NSHomeDirectory().stringByAppendingString("/Desktop/Debug1"), withIntermediateDirectories: true, attributes: nil) // 获取最后一个路径 let lastPath:String? = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop"))?.lastPathComponent // 删除最后一个路径 let deleteLastPath:String? = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop"))? .URLByDeletingLastPathComponent? .path // 拼接一个路径 let appendingPath:String? = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop"))? .URLByAppendingPathComponent("testFolder") .path // 文件路径分割 let pathArray:[String]? = NSURL(string: NSHomeDirectory().stringByAppendingString("/Desktop"))?.pathComponents // 文件路径组合 let pathString:NSString = NSString.pathWithComponents(pathArray!) // 将路径中的代字符 ~ 扩展成用户主目录或指定用户的主目录 // 特殊的代字符 ~ 是用户主目录(如:/Users/JHQ0228)的缩写,~linda 表示用户 linda 主目录的缩写。 let path1:NSString = "~/Desktop/test.txt"; // /Users/JHQ0228/Desktop/test.txt let mainPath:String = path1.stringByExpandingTildeInPath // 解析路径中的符号链接 /* /.. 上一级目录 */ let path2:NSString = "~/../Debug" let appPath1:String = path2.stringByResolvingSymlinksInPath // 通过解析 ~(用户主目录)、..(父目录) 、.(当前目录)和符号链接来标准化路径 /* NSHomeDirectory()/.. NSHomeDirectory() 的上一级目录 */ let path3:NSString = NSString(format:"%@/../Debug", NSHomeDirectory()) let appPath2:String = path3.stringByStandardizingPath // 获取文件拓展名 let getExtension:String? = NSURL(string: "/Desktop/test.txt")?.pathExtension // 删除文件拓展名 let deleteExtension:String? = NSURL(string: "/Desktop/test.txt")?.URLByDeletingPathExtension?.pathExtension // 拼接文件拓展名 let appendingExtension:String? = NSURL(string: "/Desktop/test.txt")?.URLByAppendingPathExtension("doc").path 2、路径判断 let nfManager = NSFileManager.defaultManager() let url1:NSURL = try! nfManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) // 判断路径是否存在 /* 如果当前路径以~开头,需使用 NSString 的 stringByExpandingTildeInPath 方法进行处理,否则会返回 false */ let bl1:Bool = nfManager.fileExistsAtPath(url1.path!) // 判断指定路径是否有可读权限 let bl2:Bool = nfManager.isReadableFileAtPath(url1.path!) // 判断指定路径是否有可写权限 let bl3:Bool = nfManager.isWritableFileAtPath(url1.path!) // 判断指定路径是否有可执行权限 let bl4:Bool = nfManager.isExecutableFileAtPath(url1.path!) // 判断指定路径是否有可删除权限 let bl5:Bool = nfManager.isDeletableFileAtPath(url1.path!) // 判断两个指定路径的内容是否相同 let bl6:Bool = nfManager.contentsEqualAtPath(url1.path!, andPath: url1.path!.stringByAppendingString("/test.txt")) 3、文件操作 let fileUrl:NSURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as! NSURL // 文件打开 // 读写 var nfHandle = NSFileHandle(forUpdatingAtPath: fileUrl.path!.stringByAppendingString("/test.txt"))! // 只读 var nfHandle1 = NSFileHandle(forReadingAtPath: fileUrl.path!.stringByAppendingString("/test.txt"))! // 只写 var nfHandle2 = NSFileHandle(forWritingAtPath: fileUrl.path!.stringByAppendingString("/test.txt"))! // 文件句柄偏移量 // 获取文件句柄指针的偏移量 let offSetNum1:UInt64 = nfHandle.offsetInFile // 将偏移量移到文件末尾,返回移动后的指针偏移量 let offSetNum2:UInt64 = nfHandle.seekToEndOfFile() // 将偏移量指向特定的位置 nfHandle.seekToFileOffset(0) // 文件读取 // 获取当前文件句柄的可用数据,获取后指针移到文件末尾 let availableData:NSData = nfHandle.availableData // 获取从当前指针位置到文件结束的所有数据,获取后指针移到文件末尾 let data1:NSData = nfHandle.readDataToEndOfFile() // 获取从当前指针位置开始读取的 length 长度的数据内容,获取后指针移到文件读取到的位置 let data2:NSData = nfHandle.readDataOfLength(10) // 文件写入 // 从当前指针位置写入数据到文件 nfHandle.writeData("你好".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!) // 文件关闭 // 关闭文件 nfHandle.closeFile() // 文件比较 let nfManager = NSFileManager.defaultManager() // 文件路径 let filePath1:String = NSHomeDirectory().stringByAppendingString("/Desktop/file1.txt") let filePath2:String = NSHomeDirectory().stringByAppendingString("/Desktop/file2.txt") nfManager.createFileAtPath(filePath1, contents: "北京欢迎您".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true), attributes: nil) nfManager.createFileAtPath(filePath2, contents: "北京欢迎".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true), attributes: nil) // 比较两个文件的内容是否相等 let bl:Bool = nfManager.contentsEqualAtPath(filePath1, andPath: filePath2)

优秀的个人博客,低调大师

iOS - Swift NSKeyedArchiver 数据归档

前言 public class NSKeyedArchiver : NSCoder public class NSKeyedUnarchiver : NSCoder 在 OC 语言中,归档是一个过程,即用某种格式来保存一个或多个对象,以便以后还原这些对象。通常,这个过程包括将(多个)对象写入文件中,以便以后读取该对象。可以使用归档的方法进行对象的深复制。 采用归档的形式来保存数据,该数据对象需要遵守 NSCoding 协议,并且该对象对应的类必须提供 encodeWithCoder: 和 initWithCoder: 方法。前一个方法告诉系统怎么对对象进行编码,而后一个方法则是告诉系统怎么对对象进行解码。 缺点:归档的形式来保存数据,只能一次性归档保存以及一次性解压。所以只能针对小量数据,而且对数据操作比较笨拙,即如果想改动数据的某一小部分,还是需要解压整个数据或者归档整个数据。 1、系统类的归档/反归档 // 文件路径 let achiverPath:String = NSHomeDirectory().stringByAppendingString("/Desktop/stringAchiverFile") // 待归档的数据 let string:String = "bei jing huan yin nin" // 归档,归档到文件 let bl:Bool = NSKeyedArchiver.archiveRootObject(string, toFile: achiverPath) // 反归档,从文件反归档 let strFromAchiverFile:AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithFile(achiverPath)! 2、自定义类的归档/反归档 Dog.swift // 遵守 NSCoding 协议 class Dog: NSObject, NSCoding { var name:String var age:Int init(name:String, age:Int) { self.name = name self.age = age } // 归档 方法 func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.name, forKey: "name") aCoder.encodeInteger(self.age, forKey: "age") } // 反归档 方法 required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as! String self.age = aDecoder.decodeIntegerForKey("age") } override var description: String{ return String(format: "%@, %d", self.name , self.age) } } main.swift // 文件路径 let achiverPath:String = NSHomeDirectory().stringByAppendingString("/Desktop/dogAchiverFile") // Dog 类需要遵守 NSCoding 协议,并实现其协议方法 let dog:Dog = Dog(name: "xiao hei", age: 2) // 归档 // 归档到文件 let bl:Bool = NSKeyedArchiver.archiveRootObject(dog, toFile: achiverPath) // 反归档 // 从文件反归档 let dogFromAchiverFile:AnyObject = NSKeyedUnarchiver.unarchiveObjectWithFile(achiverPath)! 3、NSKeyedArchiver 序列化 main.swift // 文件路径 let archiverPath:String = NSHomeDirectory().stringByAppendingString("/Desktop/catAchiverFile") // Cat 类不需要遵守 NSCoding 协议 let cat1:Cat = Cat(name: "xiao bai", age: 1) var cat2:Cat = Cat(name: "", age: 0) // 归档,编码 // 设置数据区域 let archiverData:NSMutableData = NSMutableData() // 开始存储对象,编码 // 将数据区域链接到 NSKeyedArchiver 对象 let archiver:NSKeyedArchiver = NSKeyedArchiver(forWritingWithMutableData: archiverData) // 编码 archiver.encodeInteger(cat1.age, forKey: "age") // 编码完成 archiver.finishEncoding() // 将存档的数据写入文件 let bl:Bool = archiverData.writeToFile(archiverPath, atomically: true) // 反归档,解码 // 设置数据区域 let unarchiverDataArea:NSData = NSData() // 解码存储在归档文件中的对象 // 将数据区域链接到 NSKeyedUnarchiver 对象 let unarchiver:NSKeyedUnarchiver = NSKeyedUnarchiver(forReadingWithData: unarchiverDataArea) // 解码 cat2.age = unarchiver.decodeIntegerForKey("age") // 解码完成 unarchiver.finishDecoding()

优秀的个人博客,低调大师

iOS - Swift NSUserDefaults 数据存储

前言 public class NSUserDefaults : NSObject 用来保存应用程序设置和属性、用户保存的数据。用户再次打开程序或开机后这些数据仍然存在。如果往 userDefaults 里存了一个可变数组,取出来的时候这个数组对象就变成了不可变的。 NSUserDefaults 可以存储的数据类型包括:NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary。如果要存储其他类型,则需要转换为前面的类型,才能用 NSUserDefaults 存储。 NSUserDefaults 存储的数据存储在 Library/Preferences 文件夹中 Plist 文件中。 1、NSUserDefaults 的使用 // 创建单例类对象 let userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults() 存放数据 // 存放数据 userDefaults.setObject("I Love China", forKey: "string") // 同步数据,把数据持久化到 standardUserDefaults 数据库 userDefaults.synchronize() 读取数据 // 从 userDefaults 里查询数据 let str:String = userDefaults.objectForKey("string") as! String 删除数据 // 删除数据 userDefaults.removeObjectForKey("string") // 同步数据 userDefaults.synchronize()

优秀的个人博客,低调大师

iOS - Swift Closure 闭包

1、Closure 闭包在 Swift 中非常有用。通俗的解释就是一个 Int 类型里存储着一个整数,一个 String 类型包含着一串字符,同样,闭包是一个包含着函数的类型。有了闭包,你就可以处理很多在一些古老的语言中不能处理的事情。这是因为闭包使用的多样性,比如你可以将闭包赋值给一个变量,你也可以将闭包作为一个函数的参数,你甚至可以将闭包作为一个函数的返回值。它的强大之处可见一斑。在 Swift 的很多文档教材中都说函数是“一等公民”,起初我还不是很理解“一等公民”是什么意思,但当我理解了闭包以及它的强大功能后,我恍然大悟、茅塞顿开、醍醐灌顶。原来闭包的这些特性就是“一等公民”的特性啊! 闭包是功能性自包含模块,可以在代码中被传递和使用。一段程序代码通常由常量、变量和表达式组成,然后使用一对花括号“{}” 来表示闭合并包裹着这些代码,由这对花括号包裹着的代码块就是一个闭包。Swift 中的闭包与 C 和 Objective-C 中的 Block 以及其他一些编程语言中的 lambdas 比较相似。Block 和闭包的区别只是语法的不同而已,而且闭包的可读性比较强。 闭包是引用类型,无论你将函数/闭包赋值给一个常量还是变量,实际上都是在将常量/变量设置为对应函数/闭包的引用,这也意味着如果你将闭包赋值给了两个不同的常量/变量,两个值都会指向同一个闭包。 1)在 Swift 语言中有三种闭包形式: 全局函数:是一个有名字但不会捕获任何值的闭包。 嵌套函数:是一个有名字并可以捕获到其封闭函数域内的值的闭包。 匿名闭包:闭包表达式是一个利用轻量级语法所写的,可以捕获其上下文中变量或常量值。 2)函数形式: func myConpare(s1:String, s2:String) -> Bool { return s1 > s2 } let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort(myConpare) 3)一般形式: { (parameters参数) -> returnType返回类型 in statements } 可以使用常量、变量、inout、可变参数、元组类型作为闭包的参数,但不能在闭包参数中设置默认值,定义返回值和函数返回值的类型相同。 闭包表达式中的 in 关键字表示闭包的参数和返回值类型定义已经完成,这些参数和返回值都将在下面的闭包函数体中得到处理。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort { (s1:String, s2:String) -> Bool in return s1 > s2 } 4)参数类型隐藏形式: Swift 中有类型推断的特性,所以我们可以去掉参数类型。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort { (s1, s2) -> Bool in return s1 > s2 } 5)返回值类型隐藏形式: Swift 中有类型推断的特性,所以我们可以去掉返回值类型。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort { (s1, s2) in return s1 > s2 } 6)return 隐藏形式: 单行表达式的闭包可以通过隐藏关键字 return 来隐式地将单行表达式的结果作为返回值。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort { (s1, s2) in s1 > s2 } 7)参数名省略形式: 闭包的使用非常的灵活,我们可以省略闭包参数列表中的参数的参数类型定义,被省略的参数类型会通过闭包函数的类型进行推断。同时,我们也可以在闭包函数体中通过使用闭包的参数名简写功能,直接使用 $0、$1、$2 等名字就可以引用的闭包参数值。如果同时省略了参数名和参数类型,那么 in 关键字也必须被省略,此时闭包表达式完全由闭包函数体构成。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort { $0 > $1 } 8)trailing 闭包形式: 闭包可以做其他函数的参数,而且通常都是函数的最后一个参数。但是如果作为参数的这个闭包表达式非常长,那么很有可能会影响函数调用表达式的可读性,这个时候我们就应该使用 trailing 闭包。trailing 闭包和普通闭包的不同之处在于它是一个书写在函数参数括号之外(之后)的闭包表达式,函数会自动将其作为最后一个参数调用。 当函数有且仅有一个参数,并该参数是闭包时,不但可以将闭包写在 () 外,还可以省略 ()。Swift 2.2 中可以不管参数的个数完全省略 ()。 let namesArray:Array = ["Jill", "Tim", "Chris"] let names = namesArray.sort() { $0 > $1 } 9)闭包捕获: 闭包可以在其定义的上下文中捕获常量或变量,即使定义这些常量或变量的原作用域已经不存在,仍然可以在闭包函数体内引用和修改这些常量或变量,这种机制被称为闭包捕获。在 Swift 中闭包的最简单形式是嵌套函数。嵌套函数就可以捕获其父函数的参数以及定义的常量和变量,全局函数可以捕获其上下文中的常量或变量。 func increment(amount: Int) -> (() -> Int) { var total = 0 func incrementAmount() -> Int { // total 是外部函数体内的变量,这里是可以捕获到的 total += amount return total } // 返回的是一个嵌套函数(闭包) return incrementAmount } // 闭包是引用类型,所以 incrementByTen 声明为常量也可以修改 total let incrementByTen = increment(10) incrementByTen() // return 10,incrementByTen 是一个闭包 // 这里是没有改变对 increment 的引用,所以会保存之前的值 incrementByTen() // return 20 incrementByTen() // return 30 let incrementByOne = increment(1) incrementByOne() // return 1,incrementByOne 是一个闭包 incrementByOne() // return 2 incrementByTen() // return 40 incrementByOne() // return 3

优秀的个人博客,低调大师

iOS - Swift Subscript 下标脚本

1、Subscript 下标脚本允许你通过在实例后面的方括号中传入一个或者多个的索引值来对实例进行访问和赋值。语法类似于实例方法和计算型属性的混合。与定义实例方法类似,定义下标脚本使用 subscript 关键字,显式声明入参(一个或多个)和返回类型,每个输入参数的类型也没有限制,返回值可以是任何类型,并无限制。输入参数也可以使用可变参数,但使用输入/输出(in-out)参数或和给参数设置默认值都是不允许的。与实例方法不同的是下标脚本可以设定为读写或只读。这种方式又有点像计算型属性的 getter 和 setter 方法。 下标脚本就是对一个东西通过索引,快速取值的一种语法,例如数组的 a[0]。这就是一个下标脚本。通过索引 0 来快速取值。在 Swift 中,我们可以对类(Class)、结构体(structure)和枚举(enumeration)中自己定义下标脚本的语法。 重点: 下标脚本使用 subscript 关键字来定义。 下标脚本使用 get、set 来定义读、写属性,并不需要 2 个属性都有,可以只读,并且读必须有。 定义 set 属性时,传入的参数默认名称为 newValue。并且 newValue 的类型和 subscript 函数返回值相同。 2、下标脚本的使用 2.1 下标脚本的使用 1 下标脚本的定义 struct myString { var str:String = "" subscript(start:Int, length:Int) -> String { get { return (str as NSString).substringWithRange(NSRange(location: start, length: length)) } set { str = newValue } } } 下标脚本的使用 let str1 = myString(str: "hello world") let str2 = str1[2, 5] // 输出 hello world print(str1[0, 11]) // 输出 llo w print(str2) var str3 = myString() // [0, 0] 参数无意义 str3[0, 0] = "world" // 输出 world print(str3[0, 5]) 2.2 下标脚本的使用 2 下标脚本的定义 class Student1 { var scores:[Int] = Array(count:5, repeatedValue:0) subscript(index:Int) -> Int { get { return scores[index]; } set { scores[index] = newValue } } subscript(indexs:Int...) -> [Int] { get { var values:[Int] = Array() for index in indexs { values.append(scores[index]) } return values } set { var i = 0 for index in indexs { scores[index] = newValue[i] i += 1 } } } } 下标脚本的使用 let stu1 = Student1() stu1[0] = 1 stu1[1] = 2 // 输出 a[0]:1, a[1]:2 print("a[0]:\(stu1[0]), a[1]:\(stu1[1])") let stu2 = Student1() stu2[1, 2, 3] = [5, 6, 7] // 输出 [0, 5, 6, 7, 0] print(stu2[0, 1, 2, 3, 4])

优秀的个人博客,低调大师

iOS - LocalCache 本地数据缓存

1、自定义方式本地数据缓存 1.1 自定义缓存 1 沙盒路径下的 Library/Caches 用来存放缓存文件,保存从网络下载的请求数据,后续仍然需要继续使用的文件,例如网络下载的离线数据,图片,视频文件等。该目录中的文件系统不会自动删除,可以做离线访问。它的存放时间比 tmp 下的长,但是不如 Library 下的其它目录。总的来说 Caches 目录下存放的数据不能是应用程序运行所必需的,但是能提高应用访问性能的。可写入应用支持文件,保存应用程序再次启动需要的信息。iTunes 不会对这个目录的内容进行备份。要求程序员必需提供一个完善的清除缓存目录的 "解决方案"。 Objective-C // 写缓存 - (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key { // 设置存储路径 NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key]; // 判读缓存数据是否存在 if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 删除旧的缓存数据 [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil]; } // 存储新的缓存数据 [data writeToFile:cachesPath atomically:YES]; } // 读缓存 - (NSData *)readLocalCacheDataWithKey:(NSString *)key { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key]; // 判读缓存数据是否存在 if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 读取缓存数据 return [NSData dataWithContentsOfFile:cachesPath]; } return nil; } // 删缓存 - (void)deleteLocalCacheDataWithKey:(NSString *)key { NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:key]; // 判读缓存数据是否存在 if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) { // 删除缓存数据 [[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil]; } } Swift // 写缓存 func writeLocalCacheData(data:NSData, withKey key:String) { // 设置存储路径 let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] .stringByAppendingString("/\(key)") // 判读缓存数据是否存在 if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 删除旧的缓存数据 try! NSFileManager.defaultManager().removeItemAtPath(cachesPath) } // 存储新的缓存数据 data.writeToFile(cachesPath, atomically: true) } // 读缓存 func readLocalCacheDataWithKey(key:String) -> NSData? { let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] .stringByAppendingString("/\(key)") // 判读缓存数据是否存在 if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 读取缓存数据 return NSData(contentsOfFile: cachesPath) } return nil } // 删缓存 func deleteLocalCacheDataWithKey(key:String) { let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0] .stringByAppendingString("/\(key)") // 判读缓存数据是否存在 if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) { // 删除缓存数据 try! NSFileManager.defaultManager().removeItemAtPath(cachesPath) } } 1.2 自定义缓存 2 沙盒路径下的 Library/Preferences 常用来放置配置文件、数据文件、模板等应用在运行中与用户相关,而又希望对用户不可见的文件,如系统偏好设置,用户偏好设置等文件。使用 NSUserDefaults 类进行偏好设置文件的创建、读取和修改。 Objective-C // 写缓存 - (void)saveCacheData:(NSData *)data withType:(int)type andID:(int)_id { NSUserDefaults *setting = [NSUserDefaults standardUserDefaults]; NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id]; [setting setObject:data forKey:key]; [setting synchronize]; } // 读缓存 - (NSData *)getCacheDataWithType:(int)type andID:(int)_id { NSUserDefaults * setting = [NSUserDefaults standardUserDefaults]; NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id]; return [setting objectForKey:key]; } // 删缓存 - (void)removeCacheDataWith:(int)type andID:(int)_id { NSUserDefaults * setting = [NSUserDefaults standardUserDefaults]; NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id]; [setting removeObjectForKey:key]; [setting synchronize]; } Swift // 写缓存 func saveCacheData(data:NSData, withType type:Int, andID _id:Int) { let setting = NSUserDefaults.standardUserDefaults() let key = String(format: "detail-%d-%d", type, _id) setting.setObject(data, forKey: key) setting.synchronize() } // 读缓存 func getCacheDataWithType(type:Int, andID _id:Int) -> NSData? { let setting = NSUserDefaults.standardUserDefaults() let key = String(format: "detail-%d-%d", type, _id) return setting.objectForKey(key) as? NSData } // 删缓存 func removeCacheDataWithType(type:Int, andID _id:Int) { let setting = NSUserDefaults.standardUserDefaults() let key = String(format: "detail-%d-%d", type, _id) setting.removeObjectForKey(key) setting.synchronize() } 2、EGOCache 方式本地数据缓存 EGOCache 一个简单、线程安全的基于 key-value 的缓存框架,原生支持 NSString、UI/NSImage、和 NSData,也支持储存任何实现 <NSCoding> 协议的类。 EGOCache 只有一个类,并且为单例类,只有 EGOCache.h 和 EGOCache.m 两个文件。 EGOCache 只提供了磁盘缓存,没有提供内存缓存,同时,也提供了清理缓存的方法。 EGOCache 可以设定缓存过期时间,默认是 1 天,过期的缓存在创建 EGOCache 对象时会被删除。 2.1 添加 EGOCache Github 网址:https://github.com/enormego/EGOCache EGOCache 使用 ARC Objective-C // 添加第三方库文件 EGOCache-2.1.3 // 包含头文件 #import "EGOCache.h" Swift // 添加第三方库文件 EGOCache-2.1.3 // 创建名为 “项目名-Bridging-Header.h” 的桥接头文件,如: SwiftLocalCache-Bridging-Header.h // 在 TARGETS -> Build Setting -> Swift Compiler - Code generation -> Objective-C Bridging Header 中 // 添加 “项目名/项目名-Bridging-Header.h” 路径,如: SwiftLocalCache/SwiftLocalCache-Bridging-Header.h // 在创建的桥接头文件中包含头文件 #import "EGOCache.h" 2.2 EGOCache 缓存 Objective-C // 判断缓存数据是否存在 BOOL hasLocalCache = [[EGOCache globalCache] hasCacheForKey:@"qqCache"]; // 读取缓存数据 NSData *localData = [[EGOCache globalCache] dataForKey:@"qqCache"]; // 存储缓存数据 [[EGOCache globalCache] setData:data forKey:@"qqCache"]; Swift // 判断缓存数据是否存在 let hasLocalCache = EGOCache.globalCache().hasCacheForKey("qqCache") // 读取缓存数据 let localData = EGOCache.globalCache().dataForKey("qqCache") // 存储缓存数据 EGOCache.globalCache().setData(data, forKey: "qqCache") 2.3 EGOCache 属性方法 判断缓存数据是否存在方法 // 判断指定缓存的数据是否存在 - (BOOL)hasCacheForKey:(NSString* __nonnull)key; 存储缓存数据方法 // 存储 NSData 型数据 - (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key; - (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 NSString 型数据 - (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key; - (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 UIImage 型数据 - (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key; - (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 PList 型数据 - (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key; - (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; // 存储 OBject 型数据 - (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key; - (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; 读取缓存数据方法 // 读取 NSData 型缓存数据 - (NSData* __nullable)dataForKey:(NSString* __nonnull)key; // 读取 NSString 型缓存数据 - (NSString* __nullable)stringForKey:(NSString* __nonnull)key; // 读取 UIImage 型缓存数据 - (UIImage* __nullable)imageForKey:(NSString* __nonnull)key; // 读取 PList 型缓存数据 - (NSData* __nullable)plistForKey:(NSString* __nonnull)key; // 读取 OBject 型缓存数据 - (nullable id<NSCoding>)objectForKey:(NSString* __nonnull)key; 复制缓存数据方法 // 复制指定缓存数据 - (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key; - (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key withTimeoutInterval:(NSTimeInterval)timeoutInterval; 清除缓存数据方法 // 清除全部缓存数据 - (void)clearCache; // 清除指定缓存的数据 - (void)removeCacheForKey:(NSString* __nonnull)key; 读取缓存信息方法 // 获取指定缓存的缓存时间 - (NSDate* __nullable)dateForKey:(NSString* __nonnull)key; // 获取所有缓存的 key 值 - (NSArray* __nonnull)allKeys; 创建缓存对象方法 // 这种方法创建的缓存对象不是单例类,可以自己设置缓存路径 - (nonnull instancetype)initWithCacheDirectory:(NSString* __nonnull)cacheDirectory; 缓存时间属性 // Default is 1 day @property(nonatomic) NSTimeInterval defaultTimeoutInterval;

优秀的个人博客,低调大师

iOS - 跑马灯、弹幕

1、跑马灯 具体实现代码见 GitHub 源码 QExtension QMarqueeView.h #pragma mark - QMarqueeViewDelegate /// 跑马灯内容点击处理协议 @protocol QMarqueeViewDelegate <NSObject> - (void)didClickContentAtIndex:(NSInteger)index; @end #pragma mark - QMarqueeView /// 跑马灯滚动方向枚举 typedef NS_ENUM(NSUInteger, QMarqueeViewDirection) { QMarqueeViewDirectionUp, QMarqueeViewDirectionDown, QMarqueeViewDirectionLeft, QMarqueeViewDirectionRight }; @interface QMarqueeView : UIView /// 显示的文本内容 @property (nonatomic, strong) NSArray *contentTexts; /// 显示的文本内容颜色,default is redColor @property (nonatomic, strong) UIColor *contentTextColor; /// 显示的文本内容字体,default is 15.0 @property (nonatomic, strong) UIFont *contentTextFont; /// 显示的文本内容对齐方式,default is NSTextAlignmentLeft @property (nonatomic, assign) NSTextAlignment contentTextAlign; /// 显示的图标内容,可以为 nil 不显示图标 @property (nonatomic, strong) UIImage *contentIcon; /// 动画方向,default is QMarqueeViewDirectionUp @property (nonatomic, assign) QMarqueeViewDirection animationDirection; /// 动画时间,等于 0 时不滚动 @property (nonatomic, assign) NSTimeInterval animationDuration; /// 动画停顿时间,default is 1.0 秒 @property (nonatomic, assign) NSTimeInterval animationDelay; /// 代理 @property (nonatomic, weak) id<QMarqueeViewDelegate> delegate; /** * 开始动画 */ - (void)q_startAnimation; /** * 创建跑马灯视图控件,开始滚动 * * @param frame 跑马灯对象的 frame * @param texts 显示的文本内容 * @param color 显示的文本内容颜色,default is redColor * @param font 显示的文本内容字体,default is 15.0 * @param align 显示的文本内容对齐方式,default is NSTextAlignmentLeft * @param icon 显示的图片内容 * @param direction 动画方向,default is QMarqueeViewDirectionUp * @param duration 动画时间,等于 0 时不滚动 * @param delay 动画停顿时间,default is 1.0 秒 * @param target 代理 * * @return 跑马灯视图控件 */ + (instancetype)q_marqueeViewWithFrame:(CGRect)frame texts:(NSArray *)texts color:(nullable UIColor *)color font:(nullable UIFont *)font align:(NSTextAlignment)align icon:(nullable UIImage *)icon direction:(QMarqueeViewDirection)direction duration:(NSTimeInterval)duartion delay:(NSTimeInterval)delay target:(nullable id<QMarqueeViewDelegate>)target; @end QMarqueeView.m #define SELF_WIDTH self.frame.size.width #define SELF_HEIGHT self.frame.size.height @interface QMarqueeView () /// 两个 label 循环滚动 @property (nonatomic, strong) UILabel *firstContentLabel; @property (nonatomic, strong) UILabel *secondContentLabel; /// 显示图片的视图 @property (nonatomic, strong) UIImageView *imageView; /// 当前显示的行 @property (nonatomic, assign) NSInteger currentIndex; /// 文本内容的起始位置、宽度、高度 @property (nonatomic, assign) CGFloat contentX; @property (nonatomic, assign) CGFloat contentWidth; @property (nonatomic, assign) CGFloat contentHeight; @end @implementation QMarqueeView /// 创建跑马灯视图控件,开始滚动 + (instancetype)q_marqueeViewWithFrame:(CGRect)frame texts:(NSArray *)texts color:(nullable UIColor *)color font:(nullable UIFont *)font align:(NSTextAlignment)align icon:(nullable UIImage *)icon direction:(QMarqueeViewDirection)direction duration:(NSTimeInterval)duartion delay:(NSTimeInterval)delay target:(nullable id<QMarqueeViewDelegate>)target { QMarqueeView *marqueeView = [[self alloc] initWithFrame:frame]; marqueeView.contentTexts = texts; marqueeView.contentTextColor = color; marqueeView.contentTextFont = font; marqueeView.contentTextAlign = align; marqueeView.contentIcon = icon; marqueeView.animationDirection = direction; marqueeView.animationDuration = duartion; marqueeView.animationDelay = delay; marqueeView.delegate = target; [marqueeView q_startAnimation]; return marqueeView; } /// 创建视图控件 - (void)setupView { // 父视图裁剪 self.clipsToBounds = YES; // 控件之间的间隔值 CGFloat margin = 10; // 判断是否有图标 if (self.contentIcon) { // 添加 Icon 视图 CGRect iconBackFrame = CGRectMake(0, 0, margin + SELF_HEIGHT, SELF_HEIGHT); UIView *iconBackView = [[UIView alloc] initWithFrame:iconBackFrame]; iconBackView.backgroundColor = [UIColor clearColor]; [self addSubview:iconBackView]; CGRect iconFrame = CGRectMake(margin, 0, SELF_HEIGHT, SELF_HEIGHT); self.imageView = [[UIImageView alloc] initWithFrame:iconFrame]; self.imageView.backgroundColor = [UIColor clearColor]; self.imageView.image = self.contentIcon; [iconBackView addSubview:self.imageView]; // 计算 Texts 的 frame 值 self.contentX = margin + SELF_HEIGHT; self.contentWidth = SELF_WIDTH - self.contentX - margin; } else { // 计算 Texts 的 frame 值 self.contentX = margin; self.contentWidth = SELF_WIDTH - self.contentX - margin; } self.contentHeight = SELF_HEIGHT; // 创建第一个 label CGRect frame1 = CGRectMake(0, 0, self.contentWidth, self.contentHeight); self.firstContentLabel = [[UILabel alloc] initWithFrame:frame1]; [self setLabel:self.firstContentLabel]; // 创建第二个 label if (self.animationDirection <= 1) { CGRect frame2 = CGRectMake(0, SELF_HEIGHT, self.contentWidth, self.contentHeight); self.secondContentLabel = [[UILabel alloc] initWithFrame:frame2]; [self setLabel:self.secondContentLabel]; } } /// 设置 label 属性 - (void)setLabel:(UILabel *)label { // 设置 label 背景视图 CGRect frame; if (self.contentIcon == nil && self.animationDirection > 1) { frame = CGRectMake(0, 0, SELF_WIDTH, self.contentHeight); } else { frame = CGRectMake(self.contentX, 0, self.contentWidth, self.contentHeight); } UIView *textBackView = [[UIView alloc] initWithFrame:frame]; textBackView.backgroundColor = [UIColor clearColor]; textBackView.clipsToBounds = YES; [self addSubview:textBackView]; // 设置默认值 UIColor *textColor = self.contentTextColor ? : [UIColor redColor]; UIFont *textFont = self.contentTextFont ? : [UIFont systemFontOfSize:15.0f]; NSTextAlignment textAlign = self.contentTextAlign ? : NSTextAlignmentLeft; // 设置 label 属性 label.backgroundColor = [UIColor clearColor]; label.lineBreakMode = NSLineBreakByTruncatingTail; label.textColor = textColor; label.font = textFont; label.textAlignment = textAlign; label.userInteractionEnabled = YES; UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentClick)]; [label addGestureRecognizer:tap1]; [textBackView addSubview:label]; } /// 开启滚动动画 - (void)startLoopAnimation { // 设置默认值 NSTimeInterval delay = 0; NSTimeInterval duration = 0; CGFloat currentContentWidth = self.contentWidth; // 设置第一个 label 显示的内容 self.firstContentLabel.text = self.contentTexts[self.currentIndex]; // 滚动时间为 0 时,停止滚动 if (0 == self.animationDuration) { return; } else { if (self.animationDirection > 1) { // 左右滚动 // 不停顿 delay = 0; // 计算文本内容长度 currentContentWidth = [self.firstContentLabel.text sizeWithAttributes:@{NSFontAttributeName:(self.contentTextFont ? : [UIFont systemFontOfSize:15.0f])}].width; duration = self.animationDuration * currentContentWidth / 150; } else { // 垂直滚动 // 动画停顿时间,默认为 1.0 秒 delay = self.animationDelay ? : 1.0f; duration = self.animationDuration; // 设置第二个 label 显示的内容 NSInteger secondCurrentIndex = self.currentIndex + 1; if (secondCurrentIndex > self.contentTexts.count - 1) { secondCurrentIndex = 0; } self.secondContentLabel.text = self.contentTexts[secondCurrentIndex]; } } CGFloat firstContentLastStartX = 0; CGFloat firstContentLastEndX = 0; CGFloat firstContentLastStartY = 0; CGFloat firstContentLastEndY = 0; CGFloat secondContentLastStartY = 0; CGFloat secondContentLastEndY = 0; // 判断滚动方向 switch (self.animationDirection) { case QMarqueeViewDirectionUp: { firstContentLastStartY = 0; firstContentLastEndY = -SELF_HEIGHT; secondContentLastStartY = firstContentLastStartY + SELF_HEIGHT; secondContentLastEndY = firstContentLastEndY + SELF_HEIGHT; break; } case QMarqueeViewDirectionDown: { firstContentLastStartY = 0; firstContentLastEndY = SELF_HEIGHT; secondContentLastStartY = firstContentLastStartY - SELF_HEIGHT; secondContentLastEndY = firstContentLastEndY - SELF_HEIGHT; break; } case QMarqueeViewDirectionLeft: { firstContentLastStartX = self.contentWidth; firstContentLastEndX = -currentContentWidth; break; } case QMarqueeViewDirectionRight: { firstContentLastStartX = -currentContentWidth; firstContentLastEndX = self.contentWidth; break; } default: break; } // 设置开始时的 frame CGRect frame1; CGRect frame2; if (self.animationDirection > 1) { frame1 = CGRectMake(firstContentLastStartX, 0, currentContentWidth, self.contentHeight); } else { frame1 = CGRectMake(0, firstContentLastStartY, self.contentWidth, self.contentHeight); frame2 = CGRectMake(0, secondContentLastStartY, self.contentWidth, self.contentHeight); } self.firstContentLabel.frame = frame1; self.secondContentLabel.frame = frame2; // 开始一次滚动动画 [UIView beginAnimations:@"" context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; [UIView setAnimationDuration:duration]; [UIView setAnimationDelay:delay]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(loopAnimationDidStop:finished:context:)]; // 设置结束时的 frame CGRect frame3; CGRect frame4; if (self.animationDirection > 1) { frame3 = CGRectMake(firstContentLastEndX, 0, currentContentWidth, self.contentHeight); } else { frame3 = CGRectMake(0, firstContentLastEndY, self.contentWidth, self.contentHeight); frame4 = CGRectMake(0, secondContentLastEndY, self.contentWidth, self.contentHeight); } self.firstContentLabel.frame = frame3; self.secondContentLabel.frame = frame4; // 结束一次滚动动画 [UIView commitAnimations]; } /// 一次动画结束事件响应处理 - (void)loopAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { self.currentIndex++; if (self.currentIndex >= self.contentTexts.count) { self.currentIndex = 0; } // 重新开启滚动动画 [self startLoopAnimation]; } /// 开始滚动 - (void)q_startAnimation { // 创建视图 [self setupView]; // 开启动画默认第一条信息 self.currentIndex = 0; // 开始滚动动画 [self startLoopAnimation]; } /// 文本内容点击事件处理 - (void)contentClick { if ([self.delegate respondsToSelector:@selector(didClickContentAtIndex:)]) { [self.delegate didClickContentAtIndex:self.currentIndex]; } } @end 使用 1、初始化 QMarqueeView 继承自 UIView, 初始化和 UIView 一样 // 创建跑马灯视图控件 CGRect frame = CGRectMake(0, 50, self.view.bounds.size.width, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 常规设置,QMarqueeView 继承自 UIView, 设置和 UIView 一样 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5]; [self.view addSubview:marqueeView]; 也可以使用类方法一体式创建设置 // 创建滚动视图,开始滚动 CGRect frame = CGRectMake(30, 250, self.view.bounds.size.width - 100, 30); QMarqueeView *marqueeView = [QMarqueeView q_marqueeViewWithFrame:frame texts:showList color:[UIColor whiteColor] font:nil align:NSTextAlignmentLeft icon:[UIImage imageNamed:@"waring1"] direction:QMarqueeViewDirectionDown duration:1.0 delay:0 target:self]; [self.view addSubview:marqueeView]; 2、设置显示的文本内容 文本内容存放到数组中设置 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; marqueeView.contentTexts = showList; 文本内容可选属性设置,可以设置文本内容的颜色、字体、及对齐方式 // 显示的文本内容颜色,default is redColor marqueeView.contentTextColor = [UIColor whiteColor]; // 显示的文本内容字体,default is 15.0 marqueeView.contentTextFont = [UIFont boldSystemFontOfSize:18]; // 显示的文本内容对齐方式,default is NSTextAlignmentLeft marqueeView.contentTextAlign = NSTextAlignmentCenter; 3、设置显示的图标内容 除显示文本内容外,还可以可选设置显示左侧图标 // 显示的图标内容,可以为 nil 不显示图标 marqueeView.contentIcon = [UIImage imageNamed:@"waring1"]; 4、设置动画时间 动画时间等于 0 时不进行滚动 // 设置动画时间 marqueeView.animationDuration = 5.0; 5、设置动画方向 不设置时默认向上滚动 // 设置动画方向,default is QMarqueeViewDirectionUp marqueeView.animationDirection = QMarqueeViewDirectionRight; 6、设置动画停顿时间 一次动画滚动完成后可以设置停顿时间,不设置时默认为 1.0 秒 // 设置动画停顿时间,default is 1.0 秒 marqueeView.animationDelay = 2.0; 7、设置点击回调代理 点击显示的内容时可以可选设置响应代理 // 设置代理,响应滚动视图点击 marqueeView.delegate = self; 8、开始滚动动画 添加设置完成后,开启动画 // 开始动画 [marqueeView q_startAnimation]; 1.1 垂直滚动 1、垂直滚动,左侧对齐 // 创建跑马灯视图控件 CGRect frame = CGRectMake(0, 50, self.view.bounds.size.width, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; marqueeView.contentTextFont = [UIFont boldSystemFontOfSize:18]; // 设置动画时间 marqueeView.animationDuration = 0.2; // 常规设置 marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 2、垂直滚动,中间对齐 // 创建跑马灯视图控件 CGRect frame = CGRectMake(0, 50, self.view.bounds.size.width, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; marqueeView.contentTextFont = [UIFont boldSystemFontOfSize:18]; // 设置动画时间 marqueeView.animationDuration = 0.2; // 设置显示的内容对齐方式 marqueeView.contentTextAlign = NSTextAlignmentCenter; // 常规设置 marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 3、垂直滚动,带图标 // 创建跑马灯视图控件 CGRect frame = CGRectMake(30, 150, self.view.bounds.size.width - 150, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"GitHub:QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; // 设置显示的图标 marqueeView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 marqueeView.animationDuration = 0.5; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 4、垂直滚动,向下滚动 // 创建跑马灯视图控件 CGRect frame = CGRectMake(30, 200, self.view.bounds.size.width - 150, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"GitHub:QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; marqueeView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 marqueeView.animationDuration = 0.5; // 设置动画方向 marqueeView.animationDirection = QMarqueeViewDirectionDown; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 5、垂直滚动,由类方法创建 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; // 创建跑马灯视图控件,开始滚动 CGRect frame = CGRectMake(30, 250, self.view.bounds.size.width - 100, 30); QMarqueeView *marqueeView = [QMarqueeView q_marqueeViewWithFrame:frame texts:showList color:[UIColor whiteColor] font:nil align:NSTextAlignmentLeft icon:[UIImage imageNamed:@"waring1"] direction:QMarqueeViewDirectionDown duration:1.0 delay:0 target:self]; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5]; [self.view addSubview:marqueeView]; 效果 1.2 水平滚动 1、水平滚动,向左滚动 // 创建跑马灯视图控件 CGRect frame = CGRectMake(50, 350, self.view.bounds.size.width - 100, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; marqueeView.contentTextFont = [UIFont boldSystemFontOfSize:18]; marqueeView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 marqueeView.animationDuration = 5.0; // 设置动画方向 marqueeView.animationDirection = QMarqueeViewDirectionLeft; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 2、水平滚动,向右滚动 // 创建跑马灯视图控件 CGRect frame = CGRectMake(50, 400, self.view.bounds.size.width - 100, 30); QMarqueeView *marqueeView = [[QMarqueeView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; marqueeView.contentTexts = showList; marqueeView.contentTextColor = [UIColor whiteColor]; marqueeView.contentTextFont = [UIFont boldSystemFontOfSize:18]; marqueeView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 marqueeView.animationDuration = 5.0; // 设置动画方向 marqueeView.animationDirection = QMarqueeViewDirectionRight; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:marqueeView]; // 开始滚动 [marqueeView q_startAnimation]; 效果 3、水平滚动,由类方法创建 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; // 创建跑马灯视图控件,开始滚动 CGRect frame = CGRectMake(30, 450, self.view.bounds.size.width - 60, 30); QMarqueeView *marqueeView = [QMarqueeView q_marqueeViewWithFrame:frame texts:showList color:nil font:nil align:0 icon:[UIImage imageNamed:@"waring2"] direction:QMarqueeViewDirectionLeft duration:4.0 delay:0 target:self]; // 常规设置 marqueeView.layer.cornerRadius = 15; marqueeView.layer.masksToBounds = YES; marqueeView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5]; [self.view addSubview:marqueeView]; 效果 2、弹幕 具体实现代码见 GitHub 源码 QExtension QBulletScreenView.h #pragma mark - QBulletScreenViewDelegate /// 跑马灯内容点击处理协议 @protocol QBulletScreenViewDelegate <NSObject> - (void)didClickContentAtIndex:(NSInteger)index; @end #pragma mark - QBulletScreenView /// 弹幕滚动方向枚举 typedef NS_ENUM(NSUInteger, QBulletScreenViewDirection) { QBulletScreenViewDirectionUp, QBulletScreenViewDirectionDown, QBulletScreenViewDirectionLeft, QBulletScreenViewDirectionRight }; @interface QBulletScreenView : UIView /// 显示的文本内容 @property (nonatomic, strong) NSArray *contentTexts; /// 显示的文本内容颜色,default is redColor @property (nonatomic, strong) UIColor *contentTextColor; /// 显示的文本内容字体,default is 15.0 @property (nonatomic, strong) UIFont *contentTextFont; /// 显示的图标内容,可以为 nil 不显示图标 @property (nonatomic, strong) UIImage *contentIcon; /// 动画方向,default is QBulletScreenViewDirectionLeft @property (nonatomic, assign) QBulletScreenViewDirection animationDirection; /// 动画时间,等于 0 时不滚动 @property (nonatomic, assign) NSTimeInterval animationDuration; /// 代理 @property (nonatomic, weak) id<QBulletScreenViewDelegate> delegate; /** * 开始动画 */ - (void)q_startAnimation; /** * 创建弹幕视图控件 * * @param frame 跑马灯对象的 frame * @param texts 显示的文本内容 * @param color 显示的文本内容颜色,default is redColor * @param font 显示的文本内容字体,default is 15.0 * @param icon 显示的图片内容 * @param direction 动画方向,default is QMarqueeViewDirectionUp * @param duration 动画时间,等于 0 时不滚动 * @param target 代理 * * @return 弹幕视图控件 */ + (instancetype)q_bulletScreenWithFrame:(CGRect)frame texts:(NSArray *)texts color:(nullable UIColor *)color font:(nullable UIFont *)font icon:(nullable UIImage *)icon direction:(QBulletScreenViewDirection)direction duration:(NSTimeInterval)duartion target:(nullable id<QBulletScreenViewDelegate>)target; @end QBulletScreenView.m #define SELF_WIDTH self.frame.size.width #define SELF_HEIGHT self.frame.size.height @interface QBulletScreenView () /// label @property (nonatomic, strong) UILabel *contentLabel; /// 显示图片的视图 @property (nonatomic, strong) UIImageView *imageView; /// 当前显示的行 @property (nonatomic, assign) NSInteger currentIndex; /// 文本内容的起始位置、宽度、高度 @property (nonatomic, assign) CGFloat contentX; @property (nonatomic, assign) CGFloat contentWidth; @property (nonatomic, assign) CGFloat contentHeight; /// 弹幕视图的位置、宽度、高度 @property (nonatomic, assign) CGFloat viewX; @property (nonatomic, assign) CGFloat viewY; @property (nonatomic, assign) CGFloat viewWidth; @property (nonatomic, assign) CGFloat viewHeight; @end @implementation QBulletScreenView /// 创建弹幕视图控件 + (instancetype)q_bulletScreenWithFrame:(CGRect)frame texts:(NSArray *)texts color:(nullable UIColor *)color font:(nullable UIFont *)font icon:(nullable UIImage *)icon direction:(QBulletScreenViewDirection)direction duration:(NSTimeInterval)duartion target:(nullable id<QBulletScreenViewDelegate>)target { QBulletScreenView *bulletScreenView = [[self alloc] initWithFrame:frame]; bulletScreenView.contentTexts = texts; bulletScreenView.contentTextColor = color; bulletScreenView.contentTextFont = font; bulletScreenView.contentIcon = icon; bulletScreenView.animationDirection = direction; bulletScreenView.animationDuration = duartion; bulletScreenView.delegate = target; return bulletScreenView; } /// 创建视图控件 - (void)setupView { // 父视图裁剪 self.clipsToBounds = YES; // 控件之间的间隔值 CGFloat margin = 10; // 判断是否有图标 if (self.contentIcon) { // 添加 Icon 视图 CGRect iconFrame = CGRectMake(margin, 0, SELF_HEIGHT, SELF_HEIGHT); self.imageView = [[UIImageView alloc] initWithFrame:iconFrame]; self.imageView.backgroundColor = [UIColor clearColor]; self.imageView.image = self.contentIcon; [self addSubview:self.imageView]; // 计算 Texts 的 frame 值 self.contentX = margin + SELF_HEIGHT; self.contentWidth = SELF_WIDTH - self.contentX - margin; } else { // 计算 Texts 的 frame 值 self.contentX = margin * 2; self.contentWidth = SELF_WIDTH - self.contentX - margin; } self.contentHeight = SELF_HEIGHT; self.viewHeight = SELF_HEIGHT; // 设置默认值 UIColor *textColor = self.contentTextColor ? : [UIColor redColor]; UIFont *textFont = self.contentTextFont ? : [UIFont systemFontOfSize:15.0f]; // 创建 label CGRect frame1 = CGRectMake(self.contentX, 0, self.contentWidth, self.contentHeight); self.contentLabel = [[UILabel alloc] initWithFrame:frame1]; self.contentLabel.backgroundColor = [UIColor clearColor]; self.contentLabel.lineBreakMode = NSLineBreakByTruncatingTail; self.contentLabel.textColor = textColor; self.contentLabel.font = textFont; self.contentLabel.userInteractionEnabled = YES; UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentClick)]; [self.contentLabel addGestureRecognizer:tap1]; [self addSubview:self.contentLabel]; } /// 开启滚动动画 - (void)startLoopAnimation { // 控件之间的间隔值 CGFloat margin = 10; // 设置默认值 NSTimeInterval duration = 0; CGFloat currentContentWidth = self.contentWidth; // 设置第一个 label 显示的内容 self.contentLabel.text = self.contentTexts[self.currentIndex]; // 滚动时间为 0 时,停止滚动 if (0 == self.animationDuration) { return; } else { // 计算文本内容长度 currentContentWidth = [self.contentLabel.text sizeWithAttributes:@{NSFontAttributeName:(self.contentTextFont ? : [UIFont systemFontOfSize:15.0f])}].width; CGRect frame = CGRectMake(self.contentX, 0, currentContentWidth, self.contentHeight); self.contentLabel.frame = frame; self.viewWidth = self.contentX + currentContentWidth + margin * 2; if (self.animationDirection > 1) { // 左右滚动 duration = self.animationDuration * currentContentWidth / 150; } else { // 垂直滚动 duration = self.animationDuration; } } CGFloat viewLastStartX = 0; CGFloat viewLastEndX = 0; CGFloat viewLastStartY = 0; CGFloat viewLastEndY = 0; // 判断滚动方向 switch (self.animationDirection) { case QBulletScreenViewDirectionUp: { viewLastStartY = self.superview.bounds.size.height; viewLastEndY = -self.viewHeight; break; } case QBulletScreenViewDirectionDown: { viewLastStartY = -self.viewHeight; viewLastEndY = self.superview.bounds.size.height; break; } case QBulletScreenViewDirectionLeft: { viewLastStartX = self.superview.bounds.size.width; viewLastEndX = -self.viewWidth; break; } case QBulletScreenViewDirectionRight: { viewLastStartX = -self.viewWidth; viewLastEndX = self.superview.bounds.size.width; break; } default: break; } self.viewX = self.frame.origin.x; self.viewY = self.frame.origin.y; // 设置开始时的 frame CGRect frame1; if (self.animationDirection > 1) { frame1 = CGRectMake(viewLastStartX, self.viewY, self.viewWidth, self.contentHeight); } else { frame1 = CGRectMake(self.viewX, viewLastStartY, self.viewWidth, self.contentHeight); } self.frame = frame1; // 开始一次滚动动画 [UIView beginAnimations:@"" context:nil]; [UIView setAnimationCurve:UIViewAnimationCurveLinear]; [UIView setAnimationDuration:duration]; [UIView setAnimationDelay:0]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(loopAnimationDidStop:finished:context:)]; // 设置结束时的 frame CGRect frame2; if (self.animationDirection > 1) { frame2 = CGRectMake(viewLastEndX, self.viewY, self.viewWidth, self.contentHeight); } else { frame2 = CGRectMake(self.viewX, viewLastEndY, self.viewWidth, self.contentHeight); } self.frame = frame2; // 结束一次滚动动画 [UIView commitAnimations]; } /// 一次动画结束事件响应处理 - (void)loopAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { self.currentIndex++; if (self.currentIndex >= self.contentTexts.count) { self.currentIndex = 0; } // 重新开启滚动动画 [self startLoopAnimation]; } /// 开始滚动 - (void)q_startAnimation { // 创建视图 [self setupView]; // 开启动画默认第一条信息 self.currentIndex = 0; // 开始滚动动画 [self startLoopAnimation]; } /// 文本内容点击事件处理 - (void)contentClick { if ([self.delegate respondsToSelector:@selector(didClickContentAtIndex:)]) { [self.delegate didClickContentAtIndex:self.currentIndex]; } } @end 使用 1、初始化 QBulletScreenView 继承自 UIView, 初始化和 UIView 一样 // 创建弹幕视图控件 CGRect frame = CGRectMake(0, 100, 0, 30); QBulletScreenView *bulletScreenView = [[QBulletScreenView alloc] initWithFrame:frame]; // 常规设置,QBulletScreenView 继承自 UIView, 设置和 UIView 一样 bulletScreenView.layer.cornerRadius = 15; bulletScreenView.layer.masksToBounds = YES; bulletScreenView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5]; [self.view addSubview:bulletScreenView]; 也可以使用类方法一体式创建设置 // 创建弹幕视图控件,开始滚动 CGRect frame = CGRectMake(0, 100, 0, 30); QBulletScreenView *bulletScreenView = [QBulletScreenView q_bulletScreenWithFrame:frame texts:showList color:[UIColor whiteColor] font:nil icon:[UIImage imageNamed:@"waring1"] direction:QBulletScreenViewDirectionLeft duration:5.0 target:nil]; [self.view addSubview:bulletScreenView]; 2、设置显示的文本内容 文本内容存放到数组中设置 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; bulletScreenView.contentTexts = showList; 文本内容可选属性设置,可以设置文本内容的颜色、字体 // 显示的文本内容颜色,default is redColor bulletScreenView.contentTextColor = [UIColor whiteColor]; // 显示的文本内容字体,default is 15.0 bulletScreenView.contentTextFont = [UIFont boldSystemFontOfSize:18]; 3、设置显示的图标内容 除显示文本内容外,还可以可选设置显示左侧图标 // 显示的图标内容,可以为 nil 不显示图标 bulletScreenView.contentIcon = [UIImage imageNamed:@"waring1"]; 4、设置动画时间 动画时间等于 0 时不进行滚动 // 设置动画时间 bulletScreenView.animationDuration = 5.0; 5、设置动画方向 不设置时默认向上滚动 // 设置动画方向,default is QBulletScreenViewDirectionUp bulletScreenView.animationDirection = QBulletScreenViewDirectionLeft; 6、设置点击回调代理 点击显示的内容时可以可选设置响应代理 // 设置代理,响应滚动视图点击 bulletScreenView.delegate = self; 7、开始滚动动画 添加设置完成后,开启动画 // 开始动画 [bulletScreenView q_startAnimation]; 2.1 水平向左移动 水平向左移动 // 创建弹幕视图控件 CGRect frame = CGRectMake(0, 100, 0, 30); // x, width 设置无效 QBulletScreenView *bulletScreenView = [[QBulletScreenView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; bulletScreenView.contentTexts = showList; bulletScreenView.contentTextColor = [UIColor whiteColor]; bulletScreenView.contentTextFont = [UIFont boldSystemFontOfSize:18]; bulletScreenView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 bulletScreenView.animationDuration = 5.0; // 设置动画方向 bulletScreenView.animationDirection = QBulletScreenViewDirectionLeft; // 常规设置 bulletScreenView.layer.cornerRadius = 15; bulletScreenView.layer.masksToBounds = YES; bulletScreenView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [self.view addSubview:bulletScreenView]; // 开始滚动 [bulletScreenView q_startAnimation]; 效果 2.2 水平向右移动 水平向右移动 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; // 创建弹幕视图控件 CGRect frame = CGRectMake(0, 200, 0, 30); // x, width 设置无效 QBulletScreenView *bulletScreenView = [QBulletScreenView q_bulletScreenWithFrame:frame texts:showList color:[UIColor whiteColor] font:nil icon:[UIImage imageNamed:@"waring1"] direction:QBulletScreenViewDirectionRight duration:5.0 target:nil]; // 常规设置 bulletScreenView.layer.cornerRadius = 15; bulletScreenView.layer.masksToBounds = YES; bulletScreenView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5]; [self.view addSubview:bulletScreenView]; // 开始滚动 [bulletScreenView q_startAnimation]; 效果 2.3 水平向上移动 水平向上移动 // 创建弹幕视图控件 CGRect frame = CGRectMake(10, 0, 0, 30); // y, width 设置无效 QBulletScreenView *bulletScreenView = [[QBulletScreenView alloc] initWithFrame:frame]; // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; bulletScreenView.contentTexts = showList; bulletScreenView.contentTextColor = [UIColor whiteColor]; bulletScreenView.contentTextFont = [UIFont boldSystemFontOfSize:18]; bulletScreenView.contentIcon = [UIImage imageNamed:@"waring1"]; // 设置动画时间 bulletScreenView.animationDuration = 2.0; // 设置动画方向 bulletScreenView.animationDirection = QBulletScreenViewDirectionUp; // 常规设置 bulletScreenView.layer.cornerRadius = 15; bulletScreenView.layer.masksToBounds = YES; bulletScreenView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [backView addSubview:bulletScreenView]; // 开始滚动 [bulletScreenView q_startAnimation]; 效果 2.4 水平向下移动 水平向下移动 // 设置显示的内容 NSArray *showList = @[@"1. Hello World", @"2. 欢迎大家关注哦!", @"3. GitHub:QianChia", @"4. 新浪微博:QianChia0123", @"5. 个人博客:cnblogs.com/QianChia"]; // 创建弹幕视图控件 CGRect frame = CGRectMake(10, 0, 0, 30); // y, width 设置无效 QBulletScreenView *bulletScreenView = [QBulletScreenView q_bulletScreenWithFrame:frame texts:showList color:[UIColor whiteColor] font:[UIFont boldSystemFontOfSize:18] icon:[UIImage imageNamed:@"waring1"] direction:QBulletScreenViewDirectionDown duration:2.0 target:nil]; // 常规设置 bulletScreenView.layer.cornerRadius = 15; bulletScreenView.layer.masksToBounds = YES; bulletScreenView.backgroundColor = [UIColor colorWithRed:102/255.0f green:133/255.0f blue:253/255.0f alpha:1]; [backView addSubview:bulletScreenView]; // 开始滚动 [bulletScreenView q_startAnimation]; 效果

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码