整理 Swift 開發用到的一些小技巧

2021-09-17 02:14:45 字數 2121 閱讀 2957

selector

import uikit

private extension selector

class testviewcontroller: uiviewcontroller

@objc fileprivate func open(sender: uibutton)

}

extension的方式去擴充套件selector,在會使用到selector的情況下,呼叫是極其優雅的。比如uibuttonactionnotification

uiview....

在寫乙個view的時候,通常是這樣去寫的,

let view : uiview = uiview()

view.backgroundcolor = .red

但其實,還可以用另外一種寫法:

let view : uiview = ()
這樣寫,其實可以很好的隔離**,看起來也更加方便。

另外,objective-c也有類似的寫法。

uiview *view = ();
常量,還有一些什麼鬼

swiftstruct去定義一些常量等是比較方便的。比如uifont.

在ui開發中,經常會用到一些字型。objective-c中,比較常用的是用巨集。但是巨集swift中是無法使用的,所以使用struct去定義一些常用的uifont,也是比較方便的,另外,在使用上也是更加優雅。

// 定義這樣的乙個結構體

struct fonts

// 使用

titlelabel.font = fonts.content

同樣,也適用於uicolor,比如

// 定義這樣的乙個結構體

struct colors

// 使用

label.textcolor = colors.title

對於uifontuicolor,其實也可以使用extension,對其進行擴充套件。在使用上,也更加原生優雅。比如uicolor

extension uicolor 

label.textcolor = .title

for-in

objective-c中,寫乙個for迴圈,應該是——

for(int i = 0; i < 5; i++ )
但是在swift中,寫for迴圈大多數快速遍歷的形式——for-in。其實,這個在objective-c中,也是存在的。但是在swift裡面,則多了一些變化,在配合上where關鍵字的使用,也是極大的方便。

let arr = [1,2,3]

// 第一種方式

for element in xxarr

log:123

// 第二種方式,如需使用到 序號

for i in 0..如果,配合上where的話,可以進行一些條件的判斷等

for (index, element) in arr.enumerated() where index < 2

log:0:1

1:2

StringBuffer的一些小整理

首先我們來看看stringbuffer的構造方法 stringbuffer 構造乙個其中不帶字元的字串緩衝區,其初始容量為 16 個字元。stringbuilder charsequence seq 構造乙個字串緩衝區,它包含與指定的 charsequence 相同的字元。stringbuffer ...

Swift列舉的一些小用法總結

前言 在 swift 中,列舉是乙個非常方便也非常強大的型別。我們在日常使用中也經常會使用到它。例如,我們最常見的 optional enum optional 這裡不準備介紹列舉的基本用法,只是記錄兩個比較好用的列舉用法。關聯值關聯值是將額外資訊附加到 enum case 中的一種極好的方式。例如...

java中常用到的一些小知識

轉化時間格式 string轉date string str 2007 1 18 11 12 13 dateformat dateformat new dateformat yyyy mm dd hh mm ss try catch parseexception e date格式自定義date ada...