读书笔记-《Swift语言实战入门》-应用开发部分

AppDeletegate.swift 默认方法:

// 在应用程序启动后,要执行的委托调用
application(application: UIApplication, 
  didFinishLauchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
// 在应用程序将要由活动状态切换到非活动状态时候,要执行的委托调用,如 按下 home 按钮,返回主屏幕,或全屏之间切换应用程序等。
applicationWillResignActive(application: UIApplication)
// 在应用程序已进入后台程序时,要执行的委托调用。
applicationDidEnterBackground(application: UIApplication)
// 在应用程序将要进入前台时(被激活),要执行的委托调用,刚好与 applicationWillResignActive 方法相对应。
applicationWillEnterForeground(application: UIApplication)
// 在应用程序已被激活后,要执行的委托调用,刚好与  applicationDidEnterBackground 方法相对应。
applicationDidBecomeActive(application: UIApplication)
// 在应用程序要完全退出的时候,要执行的委托调用。
applicationWillTerminate(application: UIApplication)

iOS应用初始加载的流程:

1.程序读取到info.plist中的Main storyboard file base name属性,初始化指定的storyboard

2.初始化storyboard指向的类(例如:ViewController.swift)

3.触发viewDidLoad方法,完成view的加载


Dictionary序列化与还原

// 序列化
let jsonData = try NSJSONSerialization.dataWithJSONObject(msg, 
  options: NSJSONWritingOptions.PrettyPrinted)
// 反序列化
let msg:NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData!, 
  options: .MutableContainers) as! NSDictionary

新建绑定一个UIViewController,需要在绑定的类中添加上如下代码

init(coder aDecoder: NSCoder!) {
    super.init(coder: aDecoder)
}

通过openURL调用其他程序

// 打开网页
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.baidu.com"))

// 发送短信
UIApplication.sharedApplication().openURL(NSURL(string: "sms://10086"))

// 拨打电话
UIApplication.sharedApplication().openURL(NSURL(string: "tel://10086"))

// 发送邮件
UIApplication.sharedApplication().openURL(NSURL(string: "mailto://vincent510573094@163.com"))

// 启动其他App
UIApplication.sharedApplication().openURL(NSURL(string: "myapp://i.want.you"))

// 被调用的App需要:
// 1.Info.plist中添加一项:URL types,其中的item选择URL schemas,然后填入自定义的协议名
// 2.在AppDelegate中写入如下代码:
func application(application: UIApplication, handleOpenURL url:NSURL) -> Bool {
    // 这里是调用成功后的操作
    print("\(url)")
    return true
}

使用照相机与图库

// 该ViewController类需要实现协议:UIImagePickerControllerDelegate, UINavigationControllerDelegate

// 点击按钮触发的方法
@IBAction func getImageBtnPressed(sender: AnyObject) {
    var c = UIImagePickerController()
    c.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    c.delegate = self
    self.presentViewController(c, animated: true, completion:nil)
}

// 选中图片的方法
func imagePickerController(picker: UIImagePickerController!, 
didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
    var image:UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
    iv.image = image
}


CoreData

    要使用CoreData存储数据,在创建项目时勾选Use CoreData,AppDelegate中将自动生成一系列代码

    Entity 对应的是 table

    插入数据

// 操作数据库需访问到managedObjectContext
var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext // 上下文操作对象
var row:AnyObject = NSEntityDescription.insertNEwObjectForEntityForName("Users", context) // 为实例Users插入一个对象
row.setValue("vincent", forKey: "name")
row.setValue(1, forKey: "age")
context?.save(nil) // 提交数据

    查询数据

var dataArr:Array<AnyObject>! = []
var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext // 上下文操作对象
var f = NSFetchRequest(entityName: "Users")
dataArr = context.executeFetchRequest(f, error: nil)


用户首选项(用户设置)

var ud = NSUserDefaults.standardUserDefaults()
// 设置
ud.setObject(true, forKey: "autoDownload")
// 读取
var value = ud.objectForKey("autoDownload")

加载网络数据

var resp:NSURLResponse? // HTTP响应头
var error:NSError? // 错误信息
// 同步加载
var data = NSURLConnection.sendSynchronousRequest(
  NSURLRequest(URL: NSURL(string: "http://www.baidu.com")), 
  returningResponse: &resp, error: &error)
print(data)

// 异步加载
var data_a = NSURLConnection.sendAsynchronousRequest(
  NSURLRequest(URL: NSURL(string: "http://www.baidu.com")), 
  queue: NSOperationQueue()) { (resp:returningResponse!, 
    data:NSData!, error: &error) -> Void in
    print(data_a)
}

使用NSOpearationQueue多线程

// 例子:更新进度条
let operationQueue = NSOperationQueue()
for _ in 0...Constants.maxProgress {
    operationQueue.addOperationWithBlock {
        sleep(arc4random_uniform(10)) // 睡眠一段时间
        // 将操作添加到主线程中
        NSOperationQueue.mainQueue().addOperationWithBlock {
            self.completedProgress++
            return
        }
    }
}


使键盘不遮挡输入框内容的方法 for UITextField

// 监听键盘事件
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: "handleKeyboardWillShowNotification:", 
  name: UIKeyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: "handleKeyboardWillHideNotification:", 
  name: UIKeyboardWillHideNotification, object: nil)

// 显示键盘
func handleKeyboardWillShowNotification(notification: NSNotification) {
    keyboardWillChangeFrameWithNotification(notification, showsKeyboard: true)
}
// 隐藏键盘
func handleKeyboardWillHideNotification(notification: NSNotification) {
    keyboardWillChangeFrameWithNotification(notification, showsKeyboard: false)
}

// 键盘显示/隐藏的变化
func keyboardWillChangeFrameWithNotification(notification: NSNotification, showsKeyboard: Bool) {
    let userInfo = notification.userInfo!

    let animationDuration: NSTimeInterval = (
        userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue // 键盘显示时长
        
    // Convert the keyboard frame from screen to view coordinates.
    let keyboardScreenBeginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
    let keyboardViewBeginFrame = view.convertRect(keyboardScreenBeginFrame, fromView: view.window)
    let keyboardViewEndFrame = view.convertRect(keyboardScreenEndFrame, fromView: view.window)
    let originDelta = keyboardViewEndFrame.origin.y - keyboardViewBeginFrame.origin.y // 键盘高度
        
    // The text view should be adjusted, update the constant for this constraint.
    textViewBottomLayoutGuideConstraint.constant -= originDelta // 更新textView的约束,底部距离为-键盘高度

    view.setNeedsUpdateConstraints() // 标记为需要更新视图
        
    UIView.animateWithDuration(animationDuration, 
        delay: 0, options: .BeginFromCurrentState, animations: {
        self.view.layoutIfNeeded() // 如果有需要,则更新视图
    }, completion: nil)
        
    // Scroll to the selected text once the keyboard frame changes.
    let selectedRange = textView.selectedRange // 光标位置
    textView.scrollRangeToVisible(selectedRange) // 滚动到可视范围
}

// 离开时取消监听
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, 
  object: nil)
notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, 
  object: nil)


swift多线程GCD的使用详解

转:iOS GCD使用指南 作者:Bannings

使用AVFoundation自定义相机

转:iOS上的相机捕捉  作者:huxiaoyang


UITextView 高度自适应

public func textViewDidChange(textView: UITextView) {
    let fixedWidth = textView.frame.size.width
    let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
    var newFrame = textView.frame
    newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
    textView.frame = newFrame
}

输入组件聚焦、失焦

textView.resignFirstResponder() // 失焦
textView.becomeFirstResponder() // 聚焦


设置View渐变背景

//初始化渐变层
let gradientLayer:CAGradientLayer = CAGradientLayer()
gradientLayer.frame = view.bounds
view.layer.addSublayer(gradientLayer)
//设置渐变颜色方向
gradientLayer.startPoint = CGPointMake(0, 0)
gradientLayer.endPoint = CGPointMake(0, 1)
//设定颜色组
gradientLayer.colors = [UIColor.clearColor().CGColor, UIColor(red: 0, green: 0, blue: 0, alpha: 0.8).CGColor]













    



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值