ラベル Objective-c の投稿を表示しています。 すべての投稿を表示
ラベル Objective-c の投稿を表示しています。 すべての投稿を表示

2011年6月22日水曜日

UITableViewでcellをフリックすると deleteボタンが現れるようにする

// フリックすると delete ボタンが現れる
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{
}


この1行を付け加えるとよい

2011年6月21日火曜日

UIAlertViewを使って値を入力する方法

// Create Alert 
UIAlertView* av = [UIAlertView new]; 
av.delegate = self;
av.title = @"New Folder"; 
// Add Buttons 
[av addButtonWithTitle:@"OK"]; 
[av addButtonWithTitle:@"Cancel"]; 
// Make Space for Text View 
av.message = @"\n"; 
// Adjust the frame 
CGRect frame = av.frame; 
frame.origin.y -= -100.0f; 
av.frame = frame; 


// ここで UITextFieldを追加してやる

UITextField* text 
= [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; 
text.borderStyle = UITextBorderStyleRoundedRect; 
[av addSubview:text]; 
[text becomeFirstResponder]; 

[av show]; 
NSLog(@"text->%@",text.text);
[text release];
[av release];

UITableViewの更新3種類


その1
// すべてのセクションを更新する
// reloadDataメソッドを使います。

UITableView *tv;
[tv reloadData];
その2
// 1つのセクションを更新する
// reloadSectionsメソッドの引数に更新したいセクション番号を渡します。
[tv reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
// これで1番目のセクションの内容が更新されます。
その3
// 複数のセクションを更新する
// 複数のセクションを更新する場合は、
/// reloadSectionsメソッドの引数にNSRangeを渡してあげます。
NSRange range = NSMakeRange(0, 3);
[tv reloadSections:[NSIndexSet indexSetWithIndexesInRange:range] withRowAnimation:UITableViewRowAnimationNone];
// これで1番目から3番目までのセクションの内容が更新されます。

NSDataへの変換

NSKeyedArchiverクラスのarchivedDataWithRootObjectメソッドを使います。
NSStringやNSArray、NSDictionaryなどの様々な型のオブジェクトを
NSData
オブジェクト(バイナリデータ)へ簡単に変換することができます。

復元は、
NSKeyedUnarchiverクラスのunarchiveObjectWithDataメソッドを使います。

例えば、
NSArray
型のオブジェクトobjをNSDataオブジェクトへ変換する場合は
以下のようになります。


ID *obj;
// NSDataオブジェクトへ変換(エンコード)
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:obj];
// 変換前のオブジェクトに復元(デコード)
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];

2011年6月20日月曜日

画面にタッチしたときの動作を取得 UITouch

//<<タッチ開始>>
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
NSInteger taps = [touch tapCount];
[super touchesBegan:touches withEvent:event];
NSLog(@"タップ開始 %f, %f  タップ数:%d", location.x, location.y, taps);
}

//<<タッチ移動>>
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint oldLocation = [touch previousLocationInView:self.view];
CGPoint newLocation = [touch locationInView:self.view];
[super touchesMoved:touches withEvent:event];
NSLog(@"指の動き:%f , %f から %f, %f", oldLocation.x, oldLocation.y, newLocation.x, newLocation.y);
}

//<<タッチ終了>>
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
[super touchesEnded:touches withEvent:event];
NSLog(@"タップ終了 %f, %f", location.x, location.y);
}
//指が画面から離れた際に呼び出されます。指が離れた場所を取得し、ログに出力します。

2011年6月18日土曜日

NSValue CGPoint とか CGRect をオブジェクトにする(配列に入れたい)

NSValue  


以下
CGrectで説明 CGPointでも同じやり方です。

int x,y,w,h;
CGRect rect = CGRectMake(x,y,w,h);
NSValue *rectValue = [NSValue valueWithCGRect:rect];


NSArray *ar = [NSArray arrayWithObject:rectValue];


// NSValueからCGRectを取り出す場合は
rect = [rectValue CGRectValue];


NSValueのメソッド定義

+ (NSValue *)valueWithCGPoint:(CGPoint)point;
+ (NSValue *)valueWithCGSize:(CGSize)size;
+ (NSValue *)valueWithCGRect:(CGRect)rect;
+ (NSValue *)valueWithCGAffineTransform:(CGAffineTransform)transform;
+ (NSValue *)valueWithUIEdgeInsets:(UIEdgeInsets)insets;


2011年6月17日金曜日

AppDelegateの参照方法

#import "ast3AppDelegate.h"



ast3AppDelegate *appDelegate = (ast3AppDelegate *)[[UIApplication sharedApplication] delegate];


UIPickerViewの初期値の設定

iPhone UIPickerViewの初期値
UIPickerViewで初期値を決める方法が判らなかったのでメモ。
int row = 25; 
int compNum = 0;

[picker selectRow:row inComponent:compNum animated:YES];

// selectRow:初期値にしたい値
// inComponent:何番目のドラムロールか

NSDate から年月日時分を取り出す。

// 現在の日時を取得
NSDate *date = [NSDate date];
// デフォルトのカレンダーを取得
NSCalendar *calendar = [NSCalendar currentCalendar];
// 日時をカレンダーで年月日時分秒に分解する
NSDateComponents *dateComps 
= [calendar components:NSYearCalendarUnit   | 
  NSMonthCalendarUnit  |
  NSDayCalendarUnit    | 
  NSHourCalendarUnit   |
  NSMinuteCalendarUnit | 
  NSSecondCalendarUnit
  fromDate:date];

NSLog(@"%d/%02d/%02d %02d:%02d:%02d", 
  dateComps.year,
  dateComps.month,
  dateComps.day,
  dateComps.hour,
  dateComps.minute,
  dateComps.second);

NSString 文字列比較  同じ文字列かどうかの比較

// 文字列比較 objective-c
// 同じ文字列かどうか
NSString *str_a = @"あいうえお";
NSString *str_b = @"あいうえお";
if ([str_a isEqualToString:str_b]){
printf("str01 と str01b は同じ文字列です。\n");
}

NSString 文字列切り取りの方法

// 文字列切り取り objective-c
NSString *str = @"きっとよくなる";
[str substringWithRange:NSMakeRange(2,1)];

// >>>>>と


NSString ファイル書き込み

// NSString ファイル書き込み
NSString *testtest = @"abcefg\nhijklmn";
[testtest writeToFile:@"/doc/123.txt" atomically:YES encoding:NSUTF16StringEncoding error:nil];

NSString 文字列検索

// NSString 文字列検索
//(8)文字列内で、ある文字列を検索
NSString *str01 =@"あいうえお";
NSRange searchResult = [str01 rangeOfString:@"うえ"];

if (searchResult.location == NSNotFound) {
printf("見つかりません");
} else {
printf("Position: %d, Length: %d です。\n",
  searchResult.location, searchResult.length);
}

NSDateの使い方いろいろ

/*
NSDate
■クラスの構造
[Foundation Class]
-NSObject
-NSDate
-NSDateComponents:年月日時分秒データを保持
-NSCalendar:カレンダー
-NSLocate:地域
-NSTimeZone:時間帯
現在時刻を取得してNSString型にするにはこんな感じ
日付と時刻を扱う場合はNSDateを利用。
1970年1月1日を起点とした秒数でカウントされている。
*/
//現在時刻を取得
// フォーマットの定義
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"YYYY/MM/dd HH:mm:ss"];
// 現在時刻を取得
NSDate* now_date = [NSDate date];
// 型変換:NSDate->NSString
NSString *now_dateStr = [formatter stringFromDate:now_date];
// 型変換:NSString->char
const char *now_dateChar = [now_dateStr UTF8String];
// この型変換でその後のログ生成などの文字列操作へつながるので結構必要要素。
// ちなみに、時間を操作する場合はこんな感じ
// 現在時刻から86400秒後 = 翌日
NSDate* future_date = [NSDate dateWithTimeIntervalSinceNow:86400.0f];
// 1970/1/1起点から2678400秒後 = 起点日から1ヶ月後 1970/2/1
NSDate* old_date = [NSDate dateWithTimeIntervalSince1970:2678400.0f];
// それからNSString型で時刻を作ってNSDate型にするにはこんな感じ
// NSDate型の時刻を生成する 2008/12/04 12:06:14
// NSString型で文字列生成
NSString *setDateNSString = [NSString stringWithFormat:@"2008-12-04T12:06:14+09:00"];
// NSDate型に変換
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterFullStyle];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSDate *setDateNSDate = [dateFormatter dateFromString:setDateNSString];
// まとめてくれた人ありがとう

2011年6月16日木曜日

MKMapViewのannotationをタッチせずにコールアウトを出す

MKMapViewのannotationをタッチせずにコールアウトを出す


[mapview selectAnnotation:[mapview.annotations objectAtIndex:0] animated:YES]

MKMapViewで、addAnnotation する時に viewForAnnotation が呼び出される

[mapview addAnnotation:annotation];

addAnnotation する時に viewForAnnotationが呼び出される mapview のdelegate   viewForAnnotationです。


- (MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
NSLog(@"viewForAnnotation");
// if (annotation == mapView.userLocation) return nil;
// ここでnilを返したとすると、ピンがAnnotationに使われる
// 細かい調整は以下

MKPinAnnotationView *annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"test"];
// [annotationView setPinColor:MKPinAnnotationColorGreen];
// [annotationView setAnimatesDrop:YES];

[annotationView setCanShowCallout:YES];// > 矢印を出すか出さないか
[annotationView setRightCalloutAccessoryView:[UIButton buttonWithType:UIButtonTypeDetailDisclosure]];
//UIImage *pinImage = [UIImage imageNamed:@"pin-image.png"];
//[annotationView setImage:pinImage];
annotationView.annotation = annotation;
return annotationView;
}


> を押すと  calloutAccessoryControlTapped 呼び出されます。

- (void) mapView:(MKMapView*)_mapView annotationView:(MKAnnotationView*)annotationView calloutAccessoryControlTapped:(UIControl*)control {  
NSLog(@"タップしたときの処理 ");
// タップしたときの処理  
// annotationView.annotation でどのアノテーションか判定可能  
} 

2011年6月15日水曜日

IBOutletの位置

@interface xxxxViewController : UIViewController 
{
MyMapUIView *mymapview;
UIImageView *imagev;
}

@property(nonatomic,assign) IBOutlet UIImageView *imagev;
@property(nonatomic,assign) IBOutlet MyMapUIView *mymapview;


親のviewを消滅させたときに
dealloc に
release とかかなくてもいい。

IBOutlet

の位置は、@propertyのところに、そして、retain を assingにする。

そうすると、メモリ関連で エラーをおこしにくい & 管理しやすい。


2011年6月13日月曜日

TableViewをスクロール中でも非同期画像を表示する方法

TwitterのTLのようにネットから画像をダウンロードしてセルに追加する場合
非同期通信(NSURLConnection initwithRequest)で画像データを取得する時、
「スクロール中は画像の取得ができない」という問題が生じました。

何故かNSURLConnectionでリクエストしても 
レスポンスが帰ってくるのはスクロールが止まった時です。
それをスクロール中でもやるための方法は以下のようにすればOK.


NSURLConnection *connection;

connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];


ポイントは
1,startImmediatelyをNOに
2,scheduleInRunLoopを設定して
3,スタート
これで、スクロール中でも画像をサーバーから受信し表示することが可能になります。 

2011年6月3日金曜日

緯度経度より2地点の距離を求める

// CoreLocation.framework が必要   
// #import
 

    CLLocationCoordinate2D cordinate;
    cordinate.latitude    = 34.701909;
    cordinate.longitude    =135.4949770;
    CLLocation *nowLocation
    = [[CLLocation alloc] initWithLatitude:cordinate.latitude
                                 longitude:cordinate.longitude];
                              
    CLLocationCoordinate2D pos;
    pos.latitude    = 35.681382;
    pos.longitude    =139.766084;
    CLLocation *posLocation
    = [[CLLocation alloc] initWithLatitude:pos.latitude
                                 longitude:pos.longitude];
   
    CLLocationDistance kilometers =    [nowLocation distanceFromLocation:posLocation];
   
    NSLog(@"%f",kilometers);

2011年5月27日金曜日

URL encode

NSString メソッドで、


URL encode(%hex変換)するのが、
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc;


URL decodeするのが、
- (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc;

しかし
正解はこれ
NSString* encodeURIComponent(NSString* s) {
    return [((NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
        (CFStringRef)s,
        NULL,
        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
        kCFStringEncodingUTF8)) autorelease];
}