不明觉厉iOSiOS Developer - TipsiOS-Vendor

iOS开发中有可能用到的知识点大总结(不定期更新)

2015-11-11  本文已影响1289人  smalldu

就算在牛逼的大神也不一定有好的记性,在开发中有时候一些小点就是想不起来。这里总结下最近遇到的,不定期更新--

1、 关闭隐式动画

开发中有时候会遇到莫名其妙不希望出现的动画,肯定是系统的隐式动画再起作用,layer层属性默认是带动画的 可以用下面的方式禁掉

CATransaction.begin()
CATransaction.setDisableActions(true) // 关闭动画
//你的代码  
CATransaction.commit()
2、文件存取

在开发中有时候要本地缓存一些文件文件只能放在document文件夹下才能存取
下面是获取文件夹目录方式

let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentDirectory = paths[0]

后面加自己设定的目录就行了

下面放下我写的文件读取的方法 传入key folder等 自己摸索吧。

 //MARK: -从文件获取用户信息
    static func getUserFromDisk(key:String,folder:String)->AnyObject?{
        //反归档 获取
        let fileManager = NSFileManager.defaultManager()
        if fileManager.fileExistsAtPath(folder){
            let mdata = NSMutableData(contentsOfFile:folder )
            let unArchiver = NSKeyedUnarchiver(forReadingWithData: mdata!)
            let u = unArchiver.decodeObjectForKey(key)
            return u
        }
        return nil
    }
    
    
    static func saveModelToFile(key:String,value:AnyObject?,folder:String){
        let data = NSMutableData()
        var keyArchiver:NSKeyedArchiver!
        keyArchiver =  NSKeyedArchiver(forWritingWithMutableData: data)
        
        keyArchiver.encodeObject(value, forKey: key)
        keyArchiver.finishEncoding() //归档完毕
        
        do {
            try data.writeToFile(folder, options: NSDataWritingOptions.DataWritingAtomic)
        }catch let err{
            print("err:\(err)")
        }
    }
3、http图片或者网络不能访问

http开头苹果认为不是安全的连接,要手动配置下,在plist里加上如下代码

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
4、判断两个矩形是否相交
  CGRectIntersection(<#T##r1: CGRect##CGRect#>, <#T##r2: CGRect##CGRect#>)
5、解决添加tap手势后点击cell无响应

实现UIGestureRecognizerDelegate协议下面的方法

   func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {

        if  NSStringFromClass(touch.view!.classForCoder) == "UITableViewCellContentView"{
            return false
        }
        return true
    }
5、tableView自动布局高度自适应

至于怎么约束,不再这里讨论

tableView.estimatedRowHeight = 50  //预估高度
tableView.rowHeight = UITableViewAutomaticDimension
6、读取plist文件
    let plistPath = NSBundle.mainBundle().pathForResource("SampleData", ofType: "plist")
    if let plistPath=plistPath{
        let arr = NSArray(contentsOfFile: plistPath)        
        print(arr)
    }
7、tableView不显示多余行,不显示分割线,从xib中注册
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.tableFooterView = UIView(frame: CGRectZero)
tableView.registerNib(UINib(nibName: "homePageCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "cell")  //从nib 注册cell
8、自定义导航栏的一些属性
  //自定义一些导航栏的颜色
        UINavigationBar.appearance().barTintColor = UIColor(red: 231.0/255.0, green: 95.0/255.0, blue:
            53.0/255.0, alpha: 0.3)
        UINavigationBar.appearance().tintColor = UIColor.whiteColor()
        
        if let barFont = UIFont(name: "AvenirNextCondensed-DemiBold",
            size: 22.0) {
            UINavigationBar.appearance().titleTextAttributes =
            [NSForegroundColorAttributeName:UIColor.whiteColor(),
            NSFontAttributeName:barFont]
        }

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)  //返回按钮位空
9 、自定义tabbar的一些属性
 UIBarButtonItem.appearance().tintColor = UIColor(red: 235.0/255.0, green: 73.0/255.0, blue:
            27.0/255.0, alpha: 1.0)
 UIToolbar.appearance().barTintColor = UIColor(red: 237.0/255.0, green: 240.0/255.0, blue:
            243.0/255.0, alpha: 0.5)
10、UIImagePickerController 选择图片的简单实用(单选)
 //如果相册可用
  if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.allowsEditing = false
            imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            
            self.presentViewController(imagePicker, animated: true, completion: nil)
}
11、扩展UIImage的两个方法
extension UIImage{

    //图像比例缩放
    func scaleImage(img:UIImage,scaleSize:CGFloat)->UIImage{
        UIGraphicsBeginImageContext(CGSizeMake(img.size.width * scaleSize, img.size.height * scaleSize))
        img.drawInRect(CGRectMake(0, 0, img.size.width * scaleSize, img.size.height * scaleSize))
        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return scaledImage
    }
    
    
    //自定长宽
    func reSizeImage( toSize:CGSize)->UIImage{
        UIGraphicsBeginImageContext(CGSizeMake(toSize.width, toSize.height));
        self.drawInRect(CGRectMake(0, 0, toSize.width, toSize.height))
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return reSizeImage;
    }
}
12、空数据显示方案
import UIKit

extension UITableView{

    //MARK: -空table的解决方案
    func tableViewMsgWhenEmpty(message:String,rowCount:Int){
        if rowCount == 0{
            //没有数据
            let messageLabel = UILabel()
            // Display a message when the table is empty
            messageLabel.text = message;
            messageLabel.textColor = MAIN_COLOR
            messageLabel.numberOfLines = 0
            messageLabel.textAlignment = NSTextAlignment.Center
            messageLabel.font = UIFont.systemFontOfSize(17)
            messageLabel.sizeToFit()
            self.backgroundView = messageLabel
            messageLabel.frame = CGRectMake(0, 0, self.frame.width, self.frame.height)

            messageLabel.sizeToFit()
            self.separatorStyle = UITableViewCellSeparatorStyle.None
        }else{
            //有数据
            self.backgroundView = nil
            self.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        }
    }
    
}
13、上传照片的时候要先压缩下,不然一个图片几M 上传到服务器太浪费资源
let data = UIImageJPEGRepresentation(img,0.5)

第一个参数是UIImage对象 第二个是压缩比率 ,应该不会失真

14、对象的序列化与反序列化
class Tag: NSObject,NSCoding {

    var id:NSNumber?
    var name:String?
    
    override init() {
        
    }
    
    //MARK: -序列化
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
        aCoder.encodeObject(self.id, forKey: "id")
    }
    
    //MARK: -反序列化
    required init?(coder aDecoder: NSCoder) {
        self.id = aDecoder.decodeObjectForKey("id") as? NSNumber
        self.name = aDecoder.decodeObjectForKey("name") as? String
    }
}
15、跳转明细页的时候隐藏tabbar
let followsVC = FollowsViewController()
followsVC.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(followsVC, animated: true)
16、iOS8以上UITableCell左边不留空,一点空都没有哦
 cell.preservesSuperviewLayoutMargins = false
 cell.layoutMargins = UIEdgeInsetsZero
17、Segue相关的几个方法
//用来判断是否需要跳转
 override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
        if xxxxx == nil{
            return false
        }
        return true
    }
    
    //可以用代码 直接控制跳转
    override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) {
       
    }
    //是点击界面上的按钮 根据你绑定的跳转界面进行跳转
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
    }
18、http 请求需要在plist添加如下代码块
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
19、DM5加密
extension String{
    
    //MARK: -字符串替换
    func myreplace(oldStr:String,newStr:String)->String{
        return self.stringByReplacingOccurrencesOfString(oldStr, withString: newStr, options: NSStringCompareOptions.NumericSearch, range: nil)
    }
    
    //MARK: -MD5算法
    func md5() ->String!{
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.destroy()
        return String(format: hash as String)
    }
} 
上一篇下一篇

猜你喜欢

热点阅读