▼iPhoneプログラミングメモ▼

ラベルとイメージビュー


ラベルとイメージビュー利用するプログラムを作成する。

画像の準備
Resourcesに追加。

sample.png


ソースコードの記述
AppDelegate.h
#import 

//AppDelegateの宣言
@interface AppDelegate : UIResponder  {
    UIWindow*         _window;
    UIViewController* _viewCtl;
}

//プロパティの宣言
@property (nonatomic,retain)IBOutlet UIWindow *window;
@end

AppDelegate.m
#import "AppDelegate.h"
#import "LabelEx.h"

//AppDelegateの実装
@implementation AppDelegate

//プロパティの実装
@synthesize window=_window;

//起動時に呼ばれる
- (BOOL)application:(UIApplication*)application 
    didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {    
    //ウィンドウの生成と追加
    _window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _window.backgroundColor=[UIColor whiteColor];
    [_window makeKeyAndVisible];
    
    //ビューコントローラの生成と追加
    CGRect bounds=[[UIScreen mainScreen] bounds];
    bounds.origin.y+=20;
    bounds.size.height-=20;
    _viewCtl=[[LabelEx alloc] init]; 
    [_viewCtl.view setFrame:bounds];
    [_window addSubview:_viewCtl.view];
    return YES;
}

//メモリ解放
- (void)dealloc {
    [_viewCtl release];
    [_window release];
    [super dealloc];
}
@end

LabelEx.h
#import <UIKit/UIKit.h>

//LabelExの宣言
@interface LabelEx : UIViewController {
}
@end

LabelEx.m
#import "LabelEx.h"

//LabeExの実装
@implementation LabelEx

//ラベルの生成
- (UILabel*)makeLabel:(CGPoint)pos text:(NSString*)text font:(UIFont*)font {
    //文字列サイズの計算
    CGSize size=[text sizeWithFont:font];
    CGRect rect=CGRectMake(pos.x,pos.y,size.width,size.height);

    //ラベルの生成
    UILabel* label=[[[UILabel alloc] init] autorelease];         
    [label setFrame:rect];    
    [label setText:text];
    [label setFont:font];
    [label setTextColor:[UIColor blackColor]];
    [label setTextAlignment:UITextAlignmentLeft];
    [label setNumberOfLines:0];
    [label setLineBreakMode:UILineBreakModeWordWrap];
    [label setBackgroundColor:[UIColor clearColor]];
    return label;
}

//イメージビューの生成
- (UIImageView*)makeImageView:(CGRect)rect image:(UIImage*)image {
    UIImageView* imageView=[[[UIImageView alloc] init] autorelease];
    [imageView setFrame:rect];
    [imageView setImage:image];
    return imageView;
}

//初期化
- (void)viewDidLoad {
    [super viewDidLoad];
        
    //ラベルの生成
    UILabel* label=[self makeLabel:CGPointMake(0,0) 
        text:@"これはテストです" 
        font:[UIFont systemFontOfSize:16]];
    [self.view addSubview:label];
        
    //イメージビューの生成
    UIImageView* imageView=[self makeImageView:
        CGRectMake(0,50,80,80) 
        image:[UIImage imageNamed:@"sample.png"]];
    [self.view addSubview:imageView];
}

//画面を端末の向きにあわせて回転
- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)orientation {
    return YES;
}
@end





−戻る−