經過20天左右的學習實踐,對swift的部分內容有了一定的瞭解。下面結合自己所做的項目將這些天所學的內容進行總結。本人第一次寫博客,可能寫的比較亂。
1.Swift~UI詳解
(1)UILabel
label.textAlignment=NSTextAlignment.Center//文字位置(居中)
(2)UIButton
var btswcxy=UIButton(frame:CGRect(origin:CGPointMake(0.0,0.0),size:CGSizeMake(windowSize.width,44)))
btswcxy.backgroundColor=UIColor(patternImage:UIImage(named:"jump.png")!)//設置背景圖片(用原作者的setBackgroundImage更好一些)
btswcxy.setTitle("生物創新園",forState:UIControlState.Normal)
btswcxy.contentEdgeInsets=UIEdgeInsetsMake(0, -155, 0, 0)//文字的位置,UIEdgeInserts是相對button的frame來計算的(上、左、下、右)
btswcxy.contentHorizontalAlignment=UIControlContentHorizontalAlignment.Left//文字的位置(居左)
(3UITextField
textField.placeholder = "密碼”//提示作用
textField.secureTextEntry=true//密碼框
(4)UISegmentedControl
segControl.selectedSegmentIndex=0//選擇哪一個items
segControl.addTarget(self, action:"segmentDidchange:", forControlEvents: UIControlEvents.ValueChanged)
在響應事件segmentDidchange中可以根據segControl.selectedSegmentIndex不同的值對應顯示不同的內容。
(5)UITableView
針對下面代碼做以下兩點說明:
1.如果想要想要向右滑動時能夠delete這一行,則需將下面代碼中的註釋取消。
2.在func tableView(tableView: UITableView!, didSelectRowAtIndexPathindexPath: NSIndexPath!)函數中可以根據indexPath.row不同有不同的響應事件(即跳轉不同的界面,或根據其值請求不同的內容),本代碼中這個函數只是將其行數(indexPath.row,從第0行開始)顯示出來。
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
var tableView : UITableView?
var items :NSMutableArray?
var leftBtn:UIButton?
var ctrlsCell=["火影","海賊王","全職獵人","犬夜叉","名偵探","黑執事","吸血鬼","1","1","1","1","1","1","2","2","2","3","4"]
let windowSize = UIScreen.mainScreen().bounds.size
override func viewDidLoad() {
super.viewDidLoad()
self.items = NSMutableArray()
self.tableView = UITableView(frame:self.view.frame)
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView!)
for istring in self.ctrlsCell
{
var row = self.items!.count
var indexPath = NSIndexPath(forRow:row,inSection:0)
self.items?.addObject("1")
self.tableView?.insertRowsAtIndexPaths([indexPath], withRowAnimation:UITableViewRowAnimation.Left)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section:Int) -> Int
{
return self.items!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as UITableViewCell
cell.textLabel.text = self.ctrlsCell[indexPath.row]
//cell.backgroundColor=UIColor(patternImage:UIImage(named:"jump.png")!)
return cell
}
func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath:NSIndexPath!) -> Bool
{
return true
}
/*func tableView(tableView: UITableView!, commitEditingStyleeditingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath!)
{
self.items?.removeObjectAtIndex(indexPath.row)
self.tableView?.deleteRowsAtIndexPaths([indexPath], withRowAnimation:UITableViewRowAnimation.Top)
if (self.items!.count == 0)
{
self.leftBtn!.userInteractionEnabled = false
}
}
*/
func tableView(tableView: UITableView!, editingStyleForRowAtIndexPathindexPath: NSIndexPath!) -> UITableViewCellEditingStyle
{
return (UITableViewCellEditingStyle.Delete)
}
func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath:NSIndexPath!) -> Bool
{
return true
}
func tableView(tableView: UITableView!, moveRowAtIndexPathsourceIndexPath: NSIndexPath!, toIndexPath destinationIndexPath: NSIndexPath!)
{
self.tableView?.moveRowAtIndexPath(sourceIndexPath, toIndexPath:destinationIndexPath)
self.items?.exchangeObjectAtIndex(sourceIndexPath.row,withObjectAtIndex: destinationIndexPath.row)
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath:NSIndexPath!)
{
println("row = %d",indexPath.row)
}
}
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
var tableView : UITableView?
var items :NSMutableArray?
var leftBtn:UIButton?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "I love Swift"
self.items = NSMutableArray()
//self.items?.addObject("1","2")
// Do any additional setup after loadingthe view, typically from a nib.
setupViews()
setupRightBarButtonItem()
setupLeftBarButtonItem()
}
func setupViews()
{
self.tableView =UITableView(frame:self.view.frame)
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.registerClass(UITableViewCell.self,forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView!)
}
func setupLeftBarButtonItem()
{
self.leftBtn =UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
self.leftBtn!.frame = CGRectMake(0,0,50,40)
self.leftBtn?.setTitleColor(UIColor.redColor(),forState: UIControlState.Normal)
self.leftBtn?.setTitle("Edit",forState: UIControlState.Normal)
self.leftBtn!.tag = 100
self.leftBtn!.userInteractionEnabled =false
self.leftBtn?.addTarget(self, action:"leftBarButtonItemClicked", forControlEvents:UIControlEvents.TouchUpInside)
var barButtonItem =UIBarButtonItem(customView: self.leftBtn!)
self.navigationItem.leftBarButtonItem =barButtonItem
}
func setupRightBarButtonItem()
{
var barButtonItem = UIBarButtonItem(title:"add", style: UIBarButtonItemStyle.Plain, target: self, action:"rightBarButtonItemClicked")
self.navigationItem.rightBarButtonItem =barButtonItem
}
func rightBarButtonItemClicked()
{
var row = self.items!.count
var indexPath = NSIndexPath(forRow:row,inSection:0)
self.items?.addObject("1")
self.tableView?.insertRowsAtIndexPaths([indexPath],withRowAnimation: UITableViewRowAnimation.Left)
self.leftBtn!.userInteractionEnabled = true
}
func leftBarButtonItemClicked()
{
if (self.leftBtn!.tag == 100)
{
self.tableView?.setEditing(true, animated:true)
self.leftBtn!.tag = 200
self.leftBtn?.setTitle("Done",forState: UIControlState.Normal)
}
else
{
self.tableView?.setEditing(false, animated:true)
self.leftBtn!.tag = 100
self.leftBtn?.setTitle("Edit",forState: UIControlState.Normal)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can berecreated.
}
func tableView(tableView: UITableView,numberOfRowsInSection section: Int) -> Int
{
return self.items!.count
}
func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)as UITableViewCell
cell.textLabel.text = String(format:"%i", indexPath.row+1)
return cell
}
func tableView(tableView: UITableView!,canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool
{
return true
}
func tableView(tableView: UITableView!,commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPathindexPath: NSIndexPath!)
{
self.items?.removeObjectAtIndex(indexPath.row)
self.tableView?.deleteRowsAtIndexPaths([indexPath],withRowAnimation: UITableViewRowAnimation.Top)
if (self.items!.count == 0)
{
self.leftBtn!.userInteractionEnabled =false
}
}
func tableView(tableView: UITableView!,editingStyleForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCellEditingStyle
{
return (UITableViewCellEditingStyle.Delete)
}
func tableView(tableView: UITableView!,canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool
{
return true
}
func tableView(tableView: UITableView!,moveRowAtIndexPath sourceIndexPath: NSIndexPath!, toIndexPathdestinationIndexPath: NSIndexPath!)
{
self.tableView?.moveRowAtIndexPath(sourceIndexPath,toIndexPath: destinationIndexPath)
self.items?.exchangeObjectAtIndex(sourceIndexPath.row,withObjectAtIndex: destinationIndexPath.row)
}
func tableView(tableView: UITableView!,didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
println("row = %d",indexPath.row)
}
}
2.MD5
1、新建兩個文件,分別是NSString+MessageDigest.h和NSString+MessageDigest.m
NSString+MessageDigest.h 的內容如下:
#import <Foundation/Foundation.h>
@interface NSString (MessageDigest)
- (NSString *)md2;
- (NSString *)md4;
- (NSString *)md5;
- (NSString *)sha1;
- (NSString *)sha224;
- (NSString *)sha256;
- (NSString *)sha384;
- (NSString *)sha512;
@end
NSString+MessageDigest.m 的內容如下:
#import “NSString+MessageDigest.h”
#import <CommonCrypto/CommonCrypto.h>
typedef unsigned char*(*MessageDigestFuncPtr)(const void *data, CC_LONG len, unsigned char *md);
static NSString *_getMessageDigest(NSString*string, MessageDigestFuncPtr fp, NSUInteger length)
{
const char *cString = [string UTF8String];
unsigned char *digest =malloc(sizeof(unsigned char) * length);
fp(cString, (CC_LONG)strlen(cString),digest);
NSMutableString *hash = [NSMutableStringstringWithCapacity:length * 2];
for (int i = 0; i < length; ++i) {
[hash appendFormat:@"%02x",digest[i]];
}
free(digest);
return [hash lowercaseString];
}
@implementation NSString (MessageDigest)
- (NSString *)md2
{
return _getMessageDigest(self, CC_MD2,CC_MD2_DIGEST_LENGTH);
}
- (NSString *)md4
{
return _getMessageDigest(self, CC_MD4,CC_MD4_DIGEST_LENGTH);
}
- (NSString *)md5
{
return _getMessageDigest(self, CC_MD5,CC_MD5_DIGEST_LENGTH);
}
- (NSString *)sha1
{
return _getMessageDigest(self, CC_SHA1,CC_SHA1_DIGEST_LENGTH);
}
- (NSString *)sha224
{
return _getMessageDigest(self, CC_SHA224,CC_SHA224_DIGEST_LENGTH);
}
- (NSString *)sha256
{
return _getMessageDigest(self, CC_SHA256,CC_SHA256_DIGEST_LENGTH);
}
- (NSString *)sha384
{
return _getMessageDigest(self, CC_SHA384,CC_SHA384_DIGEST_LENGTH);
}
- (NSString *)sha512
{
return _getMessageDigest(self, CC_SHA256,CC_SHA256_DIGEST_LENGTH);
}
@end
2、在項目名-Bridging-Header.h裏面加一句 #import “NSString+MessageDigest.h”
3、使用方法如下
let aa=”string”
let bb= (aa as NSString).md5()
3.Swift封裝post和get請求
import Foundation
class HttpClient:NSObject,NSURLConnectionDataDelegate{
let SYMBOL:NSString?="AaB03x" //分界線的標識符@"AaB03x"
var connection:NSURLConnection?
//接受數據的變量
var receiveData:NSMutableData?
//上傳二進制數據的數據格式如jpg、mp3
var contentType:String!
//回調的閉包
var completeBlock:((data:NSData?,error:NSError?)->Void)?
override init() {
super.init()
receiveData=NSMutableData()
}
deinit{
}
func cancel(){
if (connection != nil){
connection!.cancel()
}
}
//get 請求
func downloadFromGetUrl(url:NSString, completionHandler:((data:NSData?,error:NSError?)->Void)){
let newUrl=NSURL(string: url)//.URLWithString(url)
let request=NSURLRequest(URL: newUrl!)
connection=NSURLConnection(request: request, delegate:self)
self.completeBlock=completionHandler
}
//post請求(dic裏沒有NSData )
func downloadFromPostUrl(url:NSString,dic:NSDictionary,completionHandler:((data:NSData?,error:NSError?)->Void)){
let newUrl=NSURL(string: url)//.URLWithString(url)
let request=NSMutableURLRequest(URL:newUrl!)
request.timeoutInterval=10.0
request.HTTPMethod="POST"
var param=NSMutableArray()
//修改後的
for key:AnyObject in dic.allKeys{
let value:NSString = dic[key as NSString] as NSString
var s=NSString(format:"\(key as NSString)=\(value)")
param.addObject(s)
}
//註釋掉的是原作者寫的
/*for key:AnyObject in dic.allKeys{
var s=NSString(format:"\(key as NSString)=\(dic[key asNSString])")
param.addObject(s)
}*/
var bodyString=param.componentsJoinedByString("&") asNSString
request.HTTPBody=bodyString.dataUsingEncoding(NSUTF8StringEncoding)
connection=NSURLConnection(request: request, delegate:self)
self.completeBlock=completionHandler
}
//post 請求(dic裏包含NSData)需要設置 contentType的類型
func downloadNSDataFromPostUrl(url:NSString,dic:NSDictionary,completionHandler:((data:NSData?,error:NSError?)->Void)){
let newUrl=NSURL(string: url)
///.URLWithString(url)
let request=NSMutableURLRequest(URL:newUrl!)
request.timeoutInterval=10.0
request.HTTPMethod="POST"
let start=NSString(format:"--\(SYMBOL)")
let end=NSString(format:"--\(SYMBOL)--")
var bodyString=NSMutableString()
var dataKey:NSString?
for key : AnyObject in dic.allKeys{
var value : AnyObject!=dic[key as NSString]
if value.isKindOfClass(NSData){
dataKey=NSString(format:"\(key)")
}else{
bodyString.appendFormat("\(start)\r\n")
//添加字段名稱,換2行
bodyString.appendFormat("Content-Disposition: form-data;name=\"\(key)\"\r\n\r\n")
//添加字段的值
bodyString.appendFormat("\(dic[key as NSString])\r\n")
}
}
//添加分界線,換行
bodyString.appendFormat("\(start)\r\n")
//聲明pic字段,文件名爲boris.png
bodyString.appendFormat("Content-Disposition: form-data;name=\"\(dataKey)\";filename=\"\(dataKey).\(contentType)\"\r\n")
//聲明上傳文件的格式
bodyString.appendFormat("Content-Type:\(contentType)\r\n\r\n")
//聲明結束符:--AaB03x--
var endStr=NSString(format:"\r\n\(end)")
//聲明myRequestData,用來放入http body
var myRequestData=NSMutableData()
//將body字符串轉化爲UTF8格式的二進制
myRequestData.appendData(bodyString.dataUsingEncoding(NSUTF8StringEncoding)!)
//將image的data加入
myRequestData.appendData(dic[dataKey!] as NSData);
//加入結束符--AaB03x--
myRequestData.appendData(endStr.dataUsingEncoding(NSUTF8StringEncoding)!);
//設置HTTPHeader中Content-Type的值
var content=NSString(format:"multipart/form-data;boundary=\(SYMBOL)")
//設置HTTPHeader
//[request setValue:contentforHTTPHeaderField:@"Content-Type"];
request.addValue(content, forHTTPHeaderField:"Content-Type")
//設置Content-Length
request.addValue(String(myRequestData.length),forHTTPHeaderField:"Content-Length")
request.HTTPBody=myRequestData
connection=NSURLConnection(request: request, delegate:self)
self.completeBlock=completionHandler
}
//NSURLConnectionDataDelegate
func connection(connection: NSURLConnection!, didReceiveResponseresponse: NSURLResponse!){
var newResponse=response as NSHTTPURLResponse
println("statusCode=\(newResponse.statusCode)")
}
funcconnection(connection: NSURLConnection!, didReceiveData data: NSData!){
receiveData!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!){
if (completeBlock != nil){
completeBlock!(data:receiveData,error:nil)
}
}
func connection(connection: NSURLConnection!, didFailWithError error:NSError!){
if (completeBlock != nil){
completeBlock!(data:receiveData,error:error)
}
}
}
get使用以及說明:
如果url爲NSURL類型可以通過下面的方法轉換爲string類型
var str_url1:String =url.absoluteString!//NSURL轉化成string
如果url中含有漢字需要Encoding,使用如下方法
var str_url =str_url1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var dict_map:NSArray
dict_map =dict?.objectForKey("map")?.objectForKey("projecctList") asNSArray//得到所有信息,格式如下圖所示,Json數據
var projectName=(dict?.objectForKey("map")?.objectForKey("projecctList")as NSArray)[0].objectForKey("projectName”) as? String
//取NSArray中第一個的projectName,以下圖爲例,那麼所取得數據爲“測試數據002”
post使用:url與上面get相同
dic中包含的鍵值對,已登陸爲例。
其中還包括了將其用戶信息存儲在本地,首先需要申明var KeepUserMg = NSUserDefaults()。
func presentTabVC(username:NSString,password:NSString) {
let username=username as String//用戶名(郵箱)
let password=password as String//密碼
//println(password)
var dl=HttpClient()
var url1:String
url1="http://61.183.11.242:8081/bioWeb/userapi?oper=login"
varurl=url1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
//post請求需要傳遞的四個參數loginId(用戶名)、userpwd(密碼)、type(用戶類型)、device(設備),參數是根據別人所給的接口的參數列表來定的。
vardic=["loginId":username,"userpwd":password,"type":"2","device":"ios"]
dl.downloadFromPostUrl(url!, dic: dic, completionHandler: {(data:NSData?, error: NSError?) -> Void in
if (error != nil){
println("error=\(error!.localizedDescription)")
}else{
vardict=NSJSONSerialization.JSONObjectWithData(data!, options:.MutableContainers,error:nil) as? NSDictionary
//println(dict)
varstr=dict?.objectForKey("code") as String//得到返回來的結果
vardetail=dict?.objectForKey("map")?.objectForKey("ApiUser")as? NSDictionary
self.usernameInfo=detail?.objectForKey("username") as?String//得到其用戶名存儲在本地
self.useremailInfo=detail?.objectForKey("email") as? String//得到其郵箱存儲在本地
if str=="success"
{
letError=UIAlertController(title: "提示", message:"登陸成功!", preferredStyle: UIAlertControllerStyle.Alert)
letbtAction=UIAlertAction(title: "確定", style:UIAlertActionStyle.Default){ action in
self.KeepUserMg.setObject(self.usernameInfo as NSString, forKey:"usernameInfo")
self.KeepUserMg.setObject(self.useremailInfo as NSString, forKey:"useremailInfo")
self.KeepUserMg.synchronize()
self.homepage()
}
Error.addAction(btAction)
self.presentViewController(Error,animated:true,completion:nil)
}
else if str =="api_login_id_empty"
{
let Error=UIAlertController(title: "提示",message: "用戶不存在!", preferredStyle: UIAlertControllerStyle.Alert)
letbtAction=UIAlertAction(title: "確定", style:UIAlertActionStyle.Default){ action in
self.logInTapped()
}
Error.addAction(btAction)
self.presentViewController(Error,animated:true,completion:nil)
}
else if str =="api_login_pwd"
{
letError=UIAlertController(title: "提示", message:"密碼錯誤!", preferredStyle: UIAlertControllerStyle.Alert)
letbtAction=UIAlertAction(title: "確定", style:UIAlertActionStyle.Default){ action in
self.logInTapped()
}
Error.addAction(btAction)
self.presentViewController(Error,animated:true,completion:nil)
}
else if str =="api_timeout"
{
letError=UIAlertController(title: "提示", message:"登陸超時!", preferredStyle: UIAlertControllerStyle.Alert)
letbtAction=UIAlertAction(title: "確定", style:UIAlertActionStyle.Default){ action in
self.logInTapped()
}
Error.addAction(btAction)
self.presentViewController(Error,animated:true,completion:nil)
}
else{
let Error=UIAlertController(title:"提示", message: "登陸失敗!",preferredStyle: UIAlertControllerStyle.Alert)
letbtAction=UIAlertAction(title: "確定", style:UIAlertActionStyle.Default){ action in
self.logInTapped()
}
Error.addAction(btAction)
self.presentViewController(Error,animated:true,completion:nil)
}
}
})
}
4.其它
頁面之間的跳轉
(1)直接跳轉到其它頁面。
varinfotzgg = TzggViewController(nibName:nil, bundle: nil)
self.presentViewController(infotzgg,animated:true,completion:nil)
(2)跳轉到其它頁面可以返回。
var infotzgg = TzggViewController(nibName: nil, bundle:nil)
self.navigationController!.pushViewController(infotzgg,animated: true)