To Learn Swift

本来一直都是用html5来做iOS开发, 在开发过程发现了很多html5中的不足, 比较纠结. 所以来折腾下Swift. 用原生代码来做框架, html来做展现视觉效果. 物尽其用, 人尽其才

键盘失去焦点

1
2
// 失去焦点, 关闭键盘
textField.resignFirstResponder()

设置图片

1
image.image = UIImage(named: imageName)

计算年龄差

1
2
var gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
var components = gregorian?.components(NSCalendarUnit.CalendarUnitYear, fromDate: birthday.date, toDate: NSDate(), options: NSCalendarOptions(0))

当触摸结束时执行

1
2
3
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
// code
}

获取slider的值

1
2
3
@IBAction func changeHeihgt(sender: AnyObject) {
height.text = String(Int((sender as! UISlider).value))
}

页面传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 主页面中监听跳转
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// 选择跳转到哪个页面
if segue.identifier == "GoToGallery" {

// 设置需要跳转到那个viewController
var vc = segue.destinationViewController as! GalleryViewController
// 设置要传输的数据
vc.val = "value"
}
}

// 当关闭页面回到主页面时的数据回传
@IBAction func close(segue: UIStoryboardSegue){

}

分享

1
2
3
4
5
6
7
8
9
10
import Social

// 创建分享对象
var controller:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeSinaWeibo)

controller.setInitialText("需要分享的内容")
// 需要分享的图片
controller.addImage(image)

self.presentViewController(controller, animated: true, completion: nil)

类型转换

1
2
3
4
5
6
7
8
// To Int
var intValue : Int = NSString(string: str).integerValue // 3

// To Float
var floatValue : Float = NSString(string: str).floatValue // 3.09999990463257

// To Double
var doubleValue : Double = NSString(string: str).doubleValue // 3.1

装载webimage

1
2
3
let url = NSURL(string: imageUrl)
let data = NSData(contentsOfURL: url!)
uiImage.image = UIImage(data: data!)

storyboard 之间的跳转, 通信

1
2
3
4
5
var storyboard = UIStoryboard(name: "Main", bundle: nil)
// MyViewController 是 storyboardId
var newVC = storyboard.instantiateViewControllerWithIdentifier("MyViewController") as! MyViewController
newVC.text = "Pass"
self.navigationController?.pushViewController(newVC, animated: false)

删除(隐藏)navigationItem

1
2
3
4
5
// 不起作用
self.navigationItem.leftBarButtonItem = nil

// 只能隐藏
self.navigationItem.hidesBackButton = true

禁止tableView滚动

1
tableView.scrollEnabled = false

使用 storyboard 配置控件参数

show the identity inspector -> User Defined Runtime Attributrs

获取字符串索引位置上的值

1
var ns3=(s as NSString).substringWithRange(NSMakeRange(4, 1))

闭包传值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
typealias sendValueClosure = (number: Int) -> Bool

// 第一个页面
func goto(number: Int) -> Bool {
println(number)
return true
}

// 第二个页面
// 需要接收goto这个指针, 赋给当前对象的闭包函数进行回调
var closure: sendValueClosure = goto

// var closure: sendValueClosure = {
// println($0)
// return true
// }

代码返回上一个view

1
2
3
4
5
6
7
8
// 返回到上一个view
navigationController?.popViewControllerAnimated(true)

// 返回到root view
navigationController?.popToRootViewControllerAnimated(true)

// 返回到指定View 数字是要返回几次
self.navigationController?.popToViewController(self.navigationController?.viewControllers[(self.navigationController?.viewControllers.count)! - 3] as! UIViewController, animated: true)

闭包 在两个view 中传递指针

1
2
3
4
5
6
7
8
9
10
11
// root view
func someFunctionThatTakesAClosure(string:String) -> Void {
print("在第二个页面调用了我")
}

vc.myClosure = someFunctionThatTakesAClosure

// next view
typealias sendValueClosure = (string:String)->Void

var myClosure:sendValueClosure?

固定电话正则

1
2
3
4
^(([1-9][0-9]{6,7})|(0[1-9]([0-9]{1,2}))-([1-9][0-9]{6,7})|(0[1-9]([0-9]{1,2}))-([1-9][0-9]{6,7})-([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})|([1-9][0-9]{6,7})-([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1}))$

// 加手机
^(([1-9][0-9]{6,7})|(0[1-9]([0-9]{1,2}))-([1-9][0-9]{6,7})|(0[1-9]([0-9]{1,2}))-([1-9][0-9]{6,7})-([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})|([1-9][0-9]{6,7})-([0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})|(1[1,3,4,5,7,8,9][0-9]{9}))$

更改TextField弹出键盘类型

1
textField.keyboardType = UIKeyboardType.NumbersAndPunctuation

新建文件夹

1
2
3
4
5
6
7
8
9
10
11
func createFolderForDocument(documentAfterPath: String){
let manager = NSFileManager.defaultManager()
let folderForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)[0] as! NSURL

var error:NSErrorPointer = nil
let folder = folderForDocument.URLByAppendingPathComponent(documentAfterPath, isDirectory: true)

if !manager.fileExistsAtPath(folder.path!) {
let createSuccess = manager.createDirectoryAtURL(folder, withIntermediateDirectories: true, attributes: nil, error: error)
}
}

获取系统信息

1
2
3
4
5
6
7
8
9
10
11
let infoDictionary = NSBundle.mainBundle().infoDictionary

let version: AnyObject? = infoDictionary!["CFBundleShortVersionString"]
let buildVerstion: AnyObject? = infoDictionary!["CFBundleVersion"]

let systemVersion : NSString = UIDevice.currentDevice().systemVersion //iOS 版本

let identifierNumber = UIDevice.currentDevice().identifierForVendor //设备 udid
let systemName = UIDevice.currentDevice().systemName //设备名称
let model = UIDevice.currentDevice().model //设备型号
let localizedModel = UIDevice.currentDevice().localizedModel //设备区域化型号 如 A1533

隐藏uiscrollview 的滚动条

1
2
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false

取消tableViewCell 选中背景颜色

1
tableViewCell.selectionStyle = UITableViewCellSelectionStyle.None

获取当前时间戳

1
NSDate().timeIntervalSince1970  // float 类型

图片转换成base64编码

1
2
3
4
var image : UIImage = UIImage(named: "image")!
var imageData = UIImagePNGRepresentation(image)

let base64String = imageData.base64EncodedStringWithOptions(.allZeros)

textview 实现 textfield Placeholder

1
2
3
4
5
6
7
8
9
10
11
12
13
func textViewDidBeginEditing(textView: UITextView) {
if textView.text == "Placeholder" {
textView.text = nil
textView.textColor = UIColor.blackColor()
}
}

func textViewDidEndEditing(textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Placeholder"
textView.textColor = UIColor.lightGrayColor()
}
}

打电话

1
2
3
if let phoneNumber = NSURL(string: "tel://13333333333") {
UIApplication.sharedApplication().openURL(phoneNumber)
}

TableView 中关闭软键盘 结束编辑

1
2
3
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.view.endEditing(true)
}

日期转时间戳

1
2
3
4
5
6
7
8
var dateString = "2014-07-15"

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)

println(date!.timeIntervalSince1970)

隐藏navigation bar 的下边线

1
2
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)

获取 UISearchbar 的输入结果

1
2
3
4
5
6
实现 UISearchBarDelegate

// MARK: 获取搜索输入结果
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
println("searchText2 \(searchBar.text)")
}

字符串切割, 截取

1
2
3
4
5
6
7
8
9
10
11
var myString: String = "hello hi";
var myStringArr = myString.componentsSeparatedByString(" ")

// 从第几位开始截取
var ns1=(s as NSString).substringFromIndex(5)
// 截取到第几位
var ns2=(s as NSString).substringToIndex(4)
// 综合上面
var ns3=(s as NSString).substringWithRange(NSMakeRange(4, 1))
// 去掉字符串的最后一个字符
(s as NSString).substringToIndex(count(s)-1)

confirm dialog

1
2
3
4
5
6
7
8
9
10
11
var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
println("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
println("Handle Cancel Logic here")
}))

presentViewController(refreshAlert, animated: true, completion: nil)

修改应用display name

1
Targets -> application -> build setting -> product name

UILabel 换行

1
2
3
4
// 显示label可以显示几行,为0表示不限制,多行显示
label.numberOfLines = 0
//NSLineBreakMode 有多个属性用来提供不同得显示格式.
label.lineBreakMode = NSLineBreakMode.ByTruncatingTail

禁止 UITextView 输入

1
self.textView.editable = false

隐藏导航栏

1
self.navigationController?.navigationBarHidden = true

清楚search bar的背景颜色

1
mySearch.searchBarStyle = UISearchBarStyle.Minimal

圆角

1
2
myVeiw.layer.cornerRadius = 20
myVeiw.layer.masksToBounds = true

边线 (边框)

1
2
myVeiw.layer.borderWidth = 1
myVeiw.layer.borderColor = UIColor.blackColor().CGColor

隐藏navigation bar

1
2
3
self.navigationController?.setNavigationBarHidden(true, animated: false)
or
self.navigationController?.navigationBar.hidden = true

去掉状态栏高度

1
self.edgesForExtendedLayout = UIRectEdge.None

tableView 点击确定行号

1
2
3
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println(indexPath.row)
}

给view设置背景图片

1
view.backgroundColor = UIColor(patternImage: UIImage(named:imageName))

四舍五入

1
lroundf(1.4)

通过Cell中的元素获取Cell的indexPath

1
tableView.indexPathForCell(sender.superview!.superview as! UICollectionViewCell)!.row

自定义了leftBarbuttonItem左滑返回手势失效

1
self.navigationController?.interactivePopGestureRecognizer.delegate = self as? UIGestureRecognizerDelegate

修改button的文本

1
button.setTitle("Button Title", forState: UIControlState.Normal)

键盘跟随TextField

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@IBOutlet var text: UITextField!
@IBOutlet var bottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {

super.viewDidLoad()

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillShow(notification : NSNotification) {

var info = notification.userInfo!
var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

UIView.animateWithDuration(0.1, animations: { () -> Void in
self.bottomConstraint.constant = -keyboardFrame.size.height
self.xxxview.layoutIfNeeded()
})
}

func keyboardWillHide(notification : NSNotification) {

self.bottomConstraint.constant = 0
self.xxxview.layoutIfNeeded()
}

注册手势

1
2
3
let tapGesture = UITapGestureRecognizer(target: self, action: "IBAction:")
tapGesture.numberOfTapsRequired = 1
view.addGestureRecognizer(tapGesture)

更改状态栏 颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 方法1: 
// plist 添加 View controller-based status bar appearance

UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent
self.navigationController?.navigationBar.barStyle = .Black

// 方法2:
// 这种在极端条件下无效
override func preferredStatusBarStyle() -> UIStatusBarStyle {

if isBool {
return UIStatusBarStyle.LightContent
}
else {
return UIStatusBarStyle.Default
}
}

// 更新状态栏
setNeedsStatusBarAppearanceUpdate()

求一个随机数

1
var temp:Int = Int(arc4random_uniform(100))+1

删除tableview section 动画效果

1
2
3
4
5
6
7
8
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

if editingStyle == UITableViewCellEditingStyle.Delete {
self.data.removeAtIndex(indexPath.section)

self.tableView.deleteSections(NSIndexSet(index: indexPath.section), withRowAnimation: .Automatic)
}
}

tableViewCell 选中后取消选中状态

1
2
3
4
5
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

// 取消选中状态
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}

音频播放

1
2
3
4
5
6
7
8
9
10
let shakeSoundMalePath = NSBundle.mainBundle().URLForResource("shake_sound_male", withExtension: "mp3")!
let error:NSError?

self.shakeSoundMale = AVAudioPlayer(contentsOfURL: shakeSoundMalePath, error: &error)

// 播放
self.shakeSoundMale.play()

// 暂停
self.shakeSoundMale.pause()

ViewController 中获取 window对象

1
let window = UIApplication.sharedApplication().keyWindow?.subviews.first as! UIView

代码生成控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let backgroundView = UIView(frame: CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)))
backgroundView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.76 )

let contentView = UIView(frame: CGRectMake((CGRectGetWidth(self.view.frame)-266.0)/2, (CGRectGetHeight(self.view.frame)-360.0)/2, 266.0, 360.0))
contentView.backgroundColor = UIColor.whiteColor()
contentView.layer.cornerRadius = 10
contentView.layer.masksToBounds = true

let imageView = UIImageView(frame: CGRectMake(0, 0, 266.0, 192.0))
imageView.image = UIImage(named: "74")!

let labelView = UILabel(frame: CGRectMake(20.0, 212.0, 226.0, 21.0))
labelView.font = UIFont.systemFontOfSize(18.0)
labelView.textColor = UIColor.blackColor()
labelView.textAlignment = .Center
labelView.text = "沙发沙发的"

let button = UIButton(frame: CGRectMake(0, 0, tableView.frame.size.width, 44))
button.setTitle("查看更多详情>>", forState: .Normal)
button.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
button.titleLabel?.font = UIFont(name: button.titleLabel!.font.fontName, size: 14)
button.backgroundColor = UIColor.whiteColor()
button.addTarget(self, action: "goToNextViewControllerOnClickAction:", forControlEvents: .TouchUpInside)

消息

1
2
3
4
5
6
7
// 注册消息
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)
// 发送消息
NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
// 删除消息
NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self)

storyboard textfield placeholder color

1
_placeholderLabel.textColor

时间戳格式化

1
2
3
4
5
6
7
8
9
10
let thisTimestamp = NSDate().timeIntervalSince1970
var outputFormat = NSDateFormatter()
let myDataSource: NSString = "1412763755"
//格式化规则
outputFormat.dateFormat = "yyyy/MM/dd HH:mm:ss"
//定义时区
outputFormat.locale = NSLocale(localeIdentifier: "shanghai")
//发布时间
let pubTime = NSDate(timeIntervalSince1970: myDataSource.doubleValue)
println(outputFormat.stringFromDate(pubTime))

数组转字典

1
enumerate(array)

字符串替换

1
2
let aString: String = "This is my string"
let newString = aString.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)

获取系统版本信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var infoDictionary = NSBundle.mainBundle().infoDictionary!

[
CFBundleName: Test1,
DTSDKName: iphonesimulator8.4,
CFBundleInfoPlistURL: Info.plist--file: ///Users/MakeHui/Library/Developer/CoreSimulator/Devices/9A1CEF33-2B69-47C7-8AEE-6D54D544795A/data/Containers/Bundle/Application/5D6882EF-6DDB-43DD-A50F-6A841CE0A011/Test1.app/,
CFBundleNumericVersion: 285245440,
UILaunchStoryboardName: LaunchScreen,
CFBundleDevelopmentRegion: en,
CFBundleVersion: 11.0.0,
DTPlatformName: iphonesimulator,
CFBundlePackageType: APPL,
UIMainStoryboardFile: Main,
CFBundleSupportedPlatforms: (iPhoneSimulator),
CFBundleShortVersionString: 10.0.0,
CFBundleInfoDictionaryVersion: 6.0,
UIRequiredDeviceCapabilities: (armv7),
CFBundleExecutable: Test1,
MinimumOSVersion: 8.4,
CFBundleIdentifier: com.huyaohui.Test1,
UIDeviceFamily: (1),
CFBundleSignature: ????,
LSRequiresIPhoneOS: 1,
UISupportedInterfaceOrientations: (UIInterfaceOrientationPortrait,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight)
]

渐隐渐现

1
2
3
4
5
UIView.animateWithDuration(5, animations: { () -> Void in
self.myView.alpha = 0.0
}, completion: { (finished: Bool) -> Void in
self.myView.hidden = true
})

修改约束的值

1
layoutConstraint.constant = 1.0

设置 navigationController 透明

1
2
3
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = true

设置Label行间距

1
2
3
4
5
6
7
8
9
var style: NSMutableParagraphStyle = NSMutableParagraphStyle()
style.lineSpacing = 12.0

let string = "阿嘎十多个阿萨德f"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: string)

attributedString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSMakeRange(0, count(string)))

self.label.attributedText = attributedString

根据地址获得在地图上描点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import MapKit
var serviceAddress = "南昌市青山湖区北京东路458号"
var geocoder = CLGeocoder()

geocoder.geocodeAddressString(self.serviceAddress, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in
if let placemark = placemarks?[0] as? CLPlacemark {

let coordinates:CLLocationCoordinate2D = placemark.location.coordinate
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01 , 0.01)
let region:MKCoordinateRegion = MKCoordinateRegionMake(coordinates, span)

self.mapView.addAnnotation(MKPlacemark(placemark: placemark))
self.mapView.setRegion(region, animated: true)
}
})

根据值查找索引位置

1
find(tabBar.items as! [UITabBarItem], item)

跳转到iTunes

1
2
3
// 使用 itms:// or itms-apps:// 协议

itms-apps://itunes.apple.com/app/id1041859549