To Learn Swift
Published: 2015-05-04 Updated: 2016-12-20
本来一直都是用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) { }
获取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" { 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 Socialvar 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 var intValue : Int = NSString (string: str).integerValue var floatValue : Float = NSString (string: str).floatValue var doubleValue : Double = NSString (string: str).doubleValue
装载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 )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 } var closure: sendValueClosure = goto
代码返回上一个view 1 2 3 4 5 6 7 8 navigationController?.popViewControllerAnimated(true ) navigationController?.popToRootViewControllerAnimated(true ) 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 func someFunctionThatTakesAClosure (string:String) -> Void { print ("在第二个页面调用了我" ) } vc.myClosure = someFunctionThatTakesAClosure 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().infoDictionarylet version: AnyObject? = infoDictionary!["CFBundleShortVersionString" ]let buildVerstion: AnyObject? = infoDictionary!["CFBundleVersion" ]let systemVersion : NSString = UIDevice .currentDevice().systemVersion let identifierNumber = UIDevice .currentDevice().identifierForVendor let systemName = UIDevice .currentDevice().systemName let model = UIDevice .currentDevice().model let localizedModel = UIDevice .currentDevice().localizedModel
1 2 scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false
取消tableViewCell 选中背景颜色 1 tableViewCell.selectionStyle = UITableViewCellSelectionStyle .None
获取当前时间戳 1 NSDate ().timeIntervalSince1970
图片转换成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 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.numberOfLines = 0 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))
四舍五入
通过Cell中的元素获取Cell的indexPath 1 tableView.indexPathForCell(sender.superview!.superview as ! UICollectionViewCell )!.row
1 self .navigationController?.interactivePopGestureRecognizer.delegate = self as ? UIGestureRecognizerDelegate
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 UIApplication .sharedApplication().statusBarStyle = UIStatusBarStyle .LightContent self .navigationController?.navigationBar.barStyle = .Black 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 ().timeIntervalSince1970var 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 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: 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 MapKitvar 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