2013年3月14日 星期四

[Xcode] 初學者筆記(一)

在撰寫我理想中程式的過程裡,遇到許多基礎書籍沒有教導如何解決的問題。因此陸續整理出來方便未來快速找到解決辦法。




1. 如何取亂數

    以骰子為例,隨機擲一個六面骰子,最簡單不需要餵給系統時間作為亂數種子的方法為:
    int num = arc4random() % (6) + 1;

2. 如何限制程式只能以直立方式(Portrait)呈現

    在一開始創建程式專案後,照下圖步驟只點選Portrait,網路上有人提到到了iOS 6.0之後就無法透過程式碼去控制portrait和landscape的啓動或禁止



3. 如何讓UILabel可以點擊觸發事件

    先在ControlView下的header檔中宣告UILabel:
    IBOutlet UILabel *eastLabel;

    再到Storyboard(故事板)中,先點選Control View再照下圖將Control View裡面所看到的eastLabel與Label圖片串聯























    接著在.m檔底下寫:

  UITapGestureRecognizer *tapEast;  //寫在外層作為global變數

  //這裡是寫在會被執行的地方,例如viewDidLoad
  tapEast = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapEastGestureCaptured:)];
  [eastLabel addGestureRecognizer:tapEast];
  [eastLabel setUserInteractionEnabled:YES];

  //實現tapEast對應執行的事件method
  - (void)tapEastNameGestureCaptured:(UITapGestureRecognizer *)gesture
  {
    //執行動作
  }




4. 如何讓UIButton可以點擊觸發事件(不是轉場喲)


    如3所提到的方式在.h檔宣告UIButton zmButton並且與Button圖形串聯後,在.m檔底下這樣寫:
    [zmButton addTarget:self action:@selector(zmClickButton:) forControlEvents:UIControlEventTouchDown];


  //實現zmButton對應執行的事件method
  -(void) zmClickButton:(id) sender
  {
    //執行動作
  }


5. 如何設定UIButton的位置、文字、和顏色

    套用4的UIButton,其設定顏色方式:

  [zmButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
   
    位置設定方式:
    zmButton.frame =  CGRectMake(60, 60100100);
 
    文字設定:
    [zmButton setTitle:@"我是按鈕" forState:UIControlStateNormal];

6. 如何讓字串與數字互換

    假如有個字串寫著"123",則可透過method轉換成數字:
    NSString *str1 = @"123";
  int number = [str1 intValue];

    再來將數字帶入字串:
  NSString *str2 = [NSString stringWithFormat:@"我是數字:%d", number];


7. 如何取得系統時間

    取得系統時間的方式是使用Xcode提供現成的物件與函式
    NSData *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"'現在時間:' yyyy.MM.dd' - 'hh:mm"];
 [timeLabel setText:[dateFormatter stringFromDate:date]];

    時間顯示的格式可以自己編輯:
    yyyy:西元年份
    MM:月
    dd:日
    hh:時
    mm:分
    ss:秒
    a:AM或PM




沒有留言:

張貼留言