常见问题处理汇总

1. tableView 中去掉多余的空行

self.tableView.tableFooterView = UIView()

2. tableView 中显示导航栏

NavigationBar 默认是不显示的需要自己设置

self.navigationController?.setNavigationBarHidden(false, animated: true)

3. Swift 中的字符串截取

let datas = "01//00"
if let locationIndex = datas.rangeOfString("//", options: NSStringCompareOptions.allZeros) {
    let data1 = datas.substringToIndex(locationIndex.startIndex)
    let data2 = datas.substringFromIndex(locationIndex.endIndex)
    println("data1=\(data1), data2=\(data2)")
    //data1=01, data2=00
}

4. 'MinuteCalendarUnit' was deprecated in iOS version 8.0: Use NSCalendarUnitMinute instead

localNotification.repeatInterval = NSCalendarUnit.MinuteCalendarUnit
        //'MinuteCalendarUnit' was deprecated in iOS version 8.0: Use NSCalendarUnitMinute instead
        //将MinuteCalendarUnit改为CalendarUnitMinute
localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute

5. 按 ID 获取 viewController

self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController

6.

//获取屏幕大小
var screenBounds:CGRect = UIScreen.mainScreen().bounds
println(screenBounds) //iPhone6输出:(0.0,0.0,375.0,667.0)

//获取屏幕大小(不包括状态栏高度)
var viewBounds:CGRect = UIScreen.mainScreen().applicationFrame
println(viewBounds) //iPhone6输出:(0.0,20.0,375.0,647.0)

7. 类型转换

//Int转换Float或Double:

let intVar : Int = 3
let doubleVar : Double = Double(intVar)


//Int转换为String:
let intVar : Int = 3
let strVar : String = String(intVar)


//String转换为Int:
let strVar : String = "123"
let intVar : Int? = strVar.toInt()

//Double转换为String:
let doubleVar : Double = 3.14
let strVar : String = String(doubleVar)

//Double保留两位小数,需要对Double进行扩展:
extension Double {
    func format(f: String) -> String {
        return NSString(format: "%\(f)f", self)
    }
}
let myDouble = 1.234567
println(myDouble.format(".2")

//String转换Double:
let strVar : String = "3.14"
var string = NSString(string: strVar)
string.doubleValue

8. 刷新页面

使用 navigationController 的 push跳转再回到主页面的时候, 刷新使用viewWillAppear() 方法

9. segue页面跳转

使用self.performSegueWithIdentifier("resultOfUrl", sender: answer)发起跳转,在

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}

中通过 sender 获取传递的参数

10.NSURL 中有中文会返回 nil

var str = "中文"
var URL = NSURL(string: "http://example.com/q=\(str)")  // nil

应该先 encode 后再使用

var str = "中文".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
var URL = NSURL(string: "http://example.com/q=\(str)")
2015-07-29 18:39183