2013年1月23日

iOS6 使用 Segue 傳輸兩個View Controller 之間的字串資料

iOS6 使用 Segue 傳輸兩個View Controller 之間的字串資料


Storyboard的設定:



在Scene1 的 TextField 輸入字串 "I love you." 按下按鈕,資料將傳到 Scene 2 的 TextField. 如下圖:

 然後在Scene2編輯後再回傳資料到Scene1,如下:

    
  


分別為這兩個ViewControllers建立兩個Classes,如下:
--------------------------------------------------------------
SceneOneViewController.h: 

#import <UIKit/UIKit.h>

@interface SceneOneViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *SceneOneTextField;
@property (strong, nonatomic) NSString *textOne;

@end


___________________________________________
SceneOneViewController.m: 


#import "SceneOneViewController.h"
#import "SceneTwoViewController.h"

@interface SceneOneViewController ()

@end

@implementation SceneOneViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//Pass data in scene one to text in scene 2
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    SceneTwoViewController *destination = [segue destinationViewController];
    destination.text = _SceneOneTextField.text;
    
}

//Receive data from scene 2 and display in scene 1; the value of var "textOne" should be set in scene 2.m
- (IBAction)returned:(UIStoryboardSegue *)segue {

    _SceneOneTextField.text = _textOne;
}

@end


注意:在Storyboard的Scene2 Controller 裡,將按鈕連到下方綠色的小方格(Exit),選擇上述的 IBAction: returned。讓它離開Scene2回到Scene1時,要執行這個動作,如下:






________________________________________________
SceneTwoViewController.h: 


#import <UIKit/UIKit.h>

@interface SceneTwoViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *SceneTwoTextField;
@property (strong, nonatomic) NSString *text;

@end
________________________________________________
SceneTwoViewController.m: 


#import "SceneTwoViewController.h"
#import "SceneOneViewController.h"

@interface SceneTwoViewController ()

@end

@implementation SceneTwoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
_SceneTwoTextField.text = _text;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//Pass the data from scene 2 to textOne
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    SceneOneViewController *destinationVC = [segue destinationViewController];
    destinationVC.textOne = _SceneTwoTextField.text;
    
}

@end



2012年10月23日

找尋 NSString 字串裡的某一個字或某一段字,將之取代為另一個字或另一段字


找尋字串裡是否含有某一個字或某一段文字,如果確定找到,將之取代為另一個字或另一段文字:

e.g.
I am in a bad mood.  ==>  I am in a good mood.
我今天心情很。  ==>   我今天心情很

*************************************************

- (void) viewDidLoad {

NSString *original = @"I am in a bad mood.";

NSLog (@"After replace, the result = %@", [self replaceStringWithSomeCharacters: original]);

}

- (NSString *) replaceStringWithSomeCharacters : (NSString *) aString{
    
 // 1. 定義要換掉的字串
    NSRange search = [aString rangeOfString:@"bad" options:NSCaseInsensitiveSearch];
  
//2. 建立一個新字串,值為 ""
    NSString *afterReplace = @"";

//3. 如果有找到要替換的"bad"
    if (search.location != NSNotFound) {

//4. 以"good" 替換掉 search 
        afterReplace = [aString stringByReplacingCharactersInRange:search withString:@"good"];

//5. 回傳替換後的結果
        return afterReplace;
    }
  
//4. 字串中找不到有"bad"的地方,回傳原來的字串
    return aString;
}

2012年10月7日

iOS -- different fonts and colors in a NSString 字串裡可以有不同的字體和顏色



讓某一個 NSString 裡可以有不同的 font 和顏色

                 



iOS 3.2 以後   iOS 6 以前  如果要達到這樣的效果,可以試一試下列的步驟:

1. 加入 CoreText.framework
2、匯入 TTTAttributedLabel.h  和  TTTAttributedLabel.m 到你的 Xcode Project
3、不要使用 UILabel; 改用 TTTAttributedLabel 的 class



QQViewController.h


#import <UIKit/UIKit.h>
#import "TTTAttributedLabel.h"

@interface QQViewController : UIViewController 
@property (strong, nonatomic) TTTAttributedLabel *label;

@end

QQViewController.m
#import "QQViewController.h"

@implementation QQViewController
@synthesize label;

- (void)viewDidLoad
{
    [super viewDidLoad];

//定義標籤框Label 的一些參數
    label = [[TTTAttributedLabel alloc] initWithFrame:CGRectMake(10, 20, 200, 100)];
    label.font = [UIFont systemFontOfSize:18];
    label.textColor = [UIColor blueColor];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 0;
    
    NSString *text = @"Lorem ipsum dolar sit amet";
    

    [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {

    //SET 3 different RANGES  設定一字串中有三個不同的範圍
    NSRange frontRange = [[mutableAttributedString string] rangeOfString:@"Lor" options:NSCaseInsensitiveSearch];
        
    NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolar" options:
            NSCaseInsensitiveSearch];

    NSRange aStressRange = NSMakeRange(24, 1);

        //SET FONT 設定字體
        //粗體
        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18];
        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
        //斜體
        UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:18];
        CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
        
        if (font) {
            //第一段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:frontRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
              (__bridge id)italicFont range:frontRange];
            
            //第二段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:boldRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:boldRange];
           
            //第三段範圍的字體
            [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName 
              range:aStressRange];//prevent memory leak
            [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:
            (__bridge id)font range:aStressRange];
            
            //自定字體
            // [mutableAttributedString addAttribute:@"TTTCustomStrikeOut" value:[NSNumber
            //  numberWithBool:YES] range:aStressRange];
            
            CFRelease(font);
        }  //end of font

        
       //SET COLOR
        //第一段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id)[[UIColor greenColor] CGColor] range:frontRange];


        //第二段範圍的字體顏色
         [mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName 
          value:(id)[[UIColor grayColor] CGColor] range:boldRange];
        
         //第三段範圍的字體顏色
        [mutableAttributedString addAttribute:(NSString *) kCTForegroundColorAttributeName 
          value:(id) [[UIColor redColor] CGColor] range:aStressRange];
        
        
        //SET CAPITAL
        [mutableAttributedString replaceCharactersInRange:boldRange withString:
          [[[mutableAttributedString string] substringWithRange:boldRange] uppercaseString]];
        
        return mutableAttributedString;
    }];
    
    [self.view addSubview:label];
    
    
    
}






iOS --.xlsx 檔轉成 .csv 檔,準備之後轉成 sqlite檔使用

以 mac 的作業系統為例:
將 excel 的 .xlsx 檔轉成 .csv 的步驟:

1. 建立一個 .xlsx 檔

 
 
 2. 另存成 .csv 檔

 3. 以 text 瀏覽器打開,在此我使用 TextWrangler 。到 Edit --> Document Options:
     
             
 4. 將它 copy 入 Xcode 的 project 裡以用建立 sqlite 檔使用。
     要確定 .csv 檔在 project 裡沒問題,可以點它,看中文有無亂碼:
     如果見到如下,就沒問題:

     學生;國文;英文
     John;89;90
     Mary;56;83
     Peter;78;54


*PS 在 .xlsx 裡輸入資料時,請不要用英文的分號 (;)。如果真的需要分號,請以中文的方式輸入(;)。這樣才能確保在程式裡轉檔成sqlite檔案時不會出問題!!!

 
 


iOS -- sqlite3 的使用順序 & query 例子



使用 sqlite3 的一般步驟:


sqlite3_open()        Open the database  打開資料庫
sqlite3_prepare()     Create the SQL statement  準備建立好的資料庫指令 (query)
sqlite3_step()        Execute the statement  執行指令
sqlite3_column()      Fetch the result  取得結果
sqlite3_finalize()    Destroy the statement  銷燬指令
sqlite3_close()       Close the database  關閉資料庫


query 例子:
1. CREATE  TABLE "main"."STARS" ("Rowid" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "Star" VARCHAR, "image" BLOB)


2. SELECT DISTINCT [column_name] FROM [table_name];

3. SELECT * FROM * WHERE * LIKE %$value%;

4. 找幾筆資料 (no. of rows in the table):
NSString *query = [NSString stringWithFormat:@"SELECT COUNT(%@) FROM %@ ", kSelectedColumn, kTablename];
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, [query UTF8String] , -1, &stmt, nil) == SQLITE_OK) {
     
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int noOfRows = (int) sqlite3_column_int(stmt, 0);
            NSLog(@"%d", noOfRows);
        }
        sqlite3_finalize(stmt2);
    } else NSLog(@"never entered!!!");
    sqlite3_close(database);



Fetch 的例子:

int sqlite3_column_count(sqlite3_stmt *pStmt);


可參考:http://www.sqlite.org/capi3ref.html

iOS -- NSString 轉 C string and vise versa



// 從 NSString 轉成 char (C 語言物件:C string):

   NSString *aStr = @"Hello CQ!";
   const char *update = [aStr cStringUsingEncoding:NSUTF8StringEncoding];
   printf("%s\n",  update);

或是:

e.g. 1
const char *ptr2 = [aStr UTF8String];
printf("%s\n", ptr2);



e.g. 2 (適用在建立 sqlite3 的query)

NSString *query = [NSString stringWithFormat:@"SELECT %@ FROM %@ WHERE %@ = %@ ORDER BY %@, destinationColumn, aTablename, aColumn, aString, ROWID";
    const char * sql = [query UTF8String];


********************************

// C string 轉  NSString

ptr = "C string to string object";
NSString *str = [NSString stringWithCString:ptr encoding:NSUTF8StringEncoding];
NSLog(@"%@", str);





2012年6月28日

如何在iOS讀出繁體中文的檔案


如何在iOS讀出繁體中文的檔案:

準備兩個檔;一個是以Big5寫的, e.g. translation01.txt
                     另一個是以UTF-8寫的,e.g. UTF8.txt





#import <Foundation/Foundation.h>

/** 讀出中文檔案內容 **/

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        NSLog(@"** begin **");
        NSString * strBig5, *strUTF8, *strUTF_8;
               
        //Big5
        NSLog(@"\n\n** 這是繁體中文Big5的實驗 **");
         NSStringEncoding encBig5 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingBig5);
        strBig5 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/translation01.txt" encoding:encBig5 error:nil];//OK
         NSLog(@"%@\n\n", strBig5);
        
        
        //UTF─8
        NSLog(@"** 這是繁體中文UTF-8的實驗 **");
        strUTF_8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@\n\n", strUTF_8);
        
        
        //UTF8:舊式
        NSLog(@"** 這是UTF8的實驗(舊式) **");
         NSStringEncoding encUTF8 = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
        strUTF8 = [[NSString alloc] initWithContentsOfFile:@"/Users/apple/Desktop/Android/Resources/txt/UTF8.txt" encoding:encUTF8 error:nil];
        NSLog(@"%@", strUTF8);
        
        
       
    }
    
    return 0;
}

結果:


2012-06-28 22:51:53.146 InitiationChap10[912:903] ** begin **
2012-06-28 22:51:53.150 InitiationChap10[912:903] 
** 這是繁體中文Big5的實驗 **
2012-06-28 22:51:53.160 InitiationChap10[912:903] 1.她是像天使般的女性。
She is an angel of a woman.
2.排山巨浪湧過來了。
A mountain of a wave came near.
3.這幾乎是不可能的。
This is all but impossible.
4.她就像是死了一樣。
She is all but dead.
5.他們並非全部都滿意這項結果。
All of them were not satisfied with the result.
2012-06-28 22:51:53.161 InitiationChap10[912:903] ** 這是繁體中文UTF-8的實驗 **
2012-06-28 22:51:53.162 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
2012-06-28 22:51:53.164 InitiationChap10[912:903] ** 這是UTF8的實驗(舊式) **
2012-06-28 22:51:53.165 InitiationChap10[912:903] 這是utf8的實驗,希望能顯示繁體中文。
Program ended with exit code: 0



P.S.
簡體中文的話,得改成:kCFStringEncodingGB_18030_2000