Swift小技巧(六)

1.如何自定義class的描述信息

class Custom: NSObject {
    override var description: String {
        return "調(diào)試信息"
    }
    override var debugDescription: String {
        return "測試輸出信息"
    }
}
let custom = Custom()
print(custom)//調(diào)試信息
print(custom.description)//調(diào)試信息
print(custom.debugDescription)//測試輸出信息

2.如何獲得app內(nèi)部的某個plist文件,并生成一個swift的字典來使用

if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
    if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
        print("可以用swift的dictionary的方式使用dict了")
    }
}

3.使用自帶的uidatepicker選擇日期

        let picker = UIDatePicker(frame: view.bounds)
        picker.datePickerMode = .dateAndTime//設(shè)置選擇的模式
        picker.addTarget(self, action: #selector(datePickerChoice(sender:)), for: .valueChanged)//添加事件

//實現(xiàn)事件
    func datePickerChoice(sender: UIDatePicker) {
        print(sender.date)
    }

在需求不明確的情況,可以使用該時間選擇器,能夠節(jié)省很多的開發(fā)時間。


屏幕快照 2017-05-09 下午3.30.03.png

4.dequeueReusableCellWithIdentifier和dequeueReusableCellWithIdentifier : forIndexPath之間的區(qū)別

1.dequeueReusableCellWithIdentifier : forIndexPath必定會返回一個cell,可能是已經(jīng)存在被重用的cell,或者是自動新建的cell
2.dequeueReusableCellWithIdentifier如果存在重用的cell,則返回,否則返回nil
3.從上面的描述,我可以知道,forIndexPath方法,必須在注冊了cell之后才能使用。而沒有forIndexPath的方法,是在沒有注冊cell的時候使用的,返回了nil之后,需要手動創(chuàng)建cell。

5.如何給button設(shè)置圓角

//給button擴展一個方法
extension UIButton {
    
    /// 添加圓角
    ///
    /// - parameter radius:      圓角半徑
    /// - parameter borderColor: 邊框顏色
    func setRoundRect(radius: CGFloat = 5, borderColor: UIColor = .clear) {
        layer.cornerRadius = radius
        layer.borderColor = borderColor.cgColor
        layer.borderWidth = 1
    }
}

6.如何判斷一個字典中,是否包含某個key

在swift中,不需要任何復(fù)雜的判斷,因為dict[key]取出來的值,是一個可選值。如果為nil,則表示,不存在該key。
所以,如果需要判斷是否存在某個key,這樣使用即可:

let dict = ["a": 1]
let keyExists = dict["a"] != nil //true存在

如果確定存在某個key,這樣使用:

let value = dict["a"]!

如果需要使用取出來的value,這樣使用即可:

if let val = dict["b"] {
    //后續(xù)代碼
}

7.swift中如何獲得PI常數(shù)

Double.pi//3.141592653589793
Float.pi//3.141593
CGFloat.pi//3.14159265358979

8.如何設(shè)置狀態(tài)欄的顏色和樣式

//在VC中重寫下列方法
    override var preferredStatusBarStyle: UIStatusBarStyle {
        //狀態(tài)欄樣式:default-黑色  lightContent-白色
        return .default
    }
    
    override var prefersStatusBarHidden: Bool {
        //狀態(tài)欄是否隱藏:true是  false不隱藏
        return true
    }

9.如何自定義tableview的headview

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
    let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
    label.font = UIFont.systemFontOfSize(14)
    label.text = list.objectAtIndex(indexPath.row) as! String
    view.addSubview(label)
    view.backgroundColor = UIColor.grayColor() // Set your background color

    return view
}

10.如何解決模擬器上面不彈出鍵盤的問題

iOS Simulator-> Hardware-> Keyboard ->取消選中該Connect Hardware Keyboard,鍵盤就會出現(xiàn)。

11.如何修改系統(tǒng)tableview的頭視圖或尾視圖的標(biāo)題文字樣式大小等

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let header = view as? UITableViewHeaderFooterView else { return }
    header.textLabel?.textColor = UIColor.red
    header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
    header.textLabel?.frame = header.frame
    header.textLabel?.textAlignment = .center
}

12.如何在類將要銷毀時做一些操作

    deinit {
        //這里執(zhí)行類要銷毀時的動作
    }

13.檢測字符串是否是空字符串

if emptyString.isEmpty {
    print("Nothing to see here")
}

14.如何獲得uitextfield的編輯事件

textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)

func textFieldDidChange(_ textField: UITextField) {
//檢查輸入等操作
}

15.如何獲得屏幕寬高等

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

16.如何過濾掉數(shù)組中相同的元素

//擴展一個方法
extension Array where Element: Equatable {
    //篩除相同的元素
    func removeDuplicates() -> [Element] {
        var result = [Element]()
        
        for value in self {
            if result.contains(value) == false {
                result.append(value)
            }
        }
        
        return result
    }
}
//使用
let arr = [2, 3, 2, 4]
arr.removeDuplicates()// [2 3 4]

17.如何實現(xiàn)兩個字典相加,生成新的字典

//擴展一個方法
extension Dictionary {
    mutating func append(other:Dictionary) {
        for (key,value) in other {
            self.updateValue(value, forKey:key)
        }
    }
}
//使用
var dic1 = [1: 2]
var dic2 = [2: 3]
dic1.append(other: dic2)//[2: 3, 1: 2]

18.為什么設(shè)置當(dāng)前頁面的navigation的backitem沒有效果?

因為baickitem是屬于上一層視圖控制器的,所以,要修改返回按鈕,需要在上一層控制器中修改

    let backItem = UIBarButtonItem()
    backItem.title = "Back"
    navigationItem.backBarButtonItem = backItem

19.如何設(shè)置,讓鍵盤彈起時,界面上移鍵盤的高度,收回時,恢復(fù)正常位置

override func viewDidLoad() {
    super.viewDidLoad()       
    //添加鍵盤彈起和收回時的通知     
    NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(Login.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)    
}
//實現(xiàn)響應(yīng)方法該變位置
func keyboardWillShow(notification: NSNotification) {        
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height
        }
    }        
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height
        }
    }
}

20.如何設(shè)置textfield的placeholder的顏色,樣式等

var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
        myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                                                               attributes: [NSForegroundColorAttributeName: UIColor.yellow])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容