UITextView控件的详细讲解


感觉写的相当不错,而且很全就直接转载了

1.创建并初始化

创建UITextView的文件,并在.h文件中写入如下代码:

 

 

#import <UIKit/UIKit.h> 

 

@interface TextViewController : UIViewController <UITextViewDelegate> 

              UITextView *textView; 

 

@property (nonatomic, retain) UITextView *textView; 

 

@end 

 

 

 

 

在.m文件中初始化这个textview,写入代码如下:

 

self.textView = [[[UITextView alloc] initWithFrame:self.view.frame]autorelease]; //初始化大小并自动释放 

 

self.textView.textColor = [UIColor blackColor];//设置textview里面的字体颜色 

 

self.textView.font = [UIFont fontWithName:@"Arial" size:18.0];//设置字体名字和字体大小 

 

self.textView.delegate = self;//设置它的委托方法 

 

self.textView.backgroundColor = [UIColor whiteColor];//设置它的背景颜色 

 

              

 

self.textView.text = @"Now is the time for all good developers tocome to serve their country.\n\nNow is the time for all good developers to cometo serve their country.";//设置它显示的内容 

 

self.textView.returnKeyType = UIReturnKeyDefault;//返回键的类型 

 

self.textView.keyboardType = UIKeyboardTypeDefault;//键盘类型 

 

self.textView.scrollEnabled = YES;//是否可以拖动 

 

              

 

self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度 

 

              

 

[self.view addSubview: self.textView];//加入到整个页面中 

 

 

 

 

2. UITextView退出键盘的几种方式

因为你点击UITextView会出现键盘,如果你退出键盘,有如下几种方式:

(1)如果你程序是有导航条的,可以在导航条上面加多一个Done的按钮,用来退出键盘,当然要先实UITextViewDelegate。

代码如下:

 

- (void)textViewDidBeginEditing:(UITextView *)textView {   

 

   UIBarButtonItem *done =    [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(leaveEditMode)] autorelease];   

 

   self.navigationItem.rightBarButtonItem = done;       

 

}   

 

- (void)textViewDidEndEditing:(UITextView *)textView {   

 

    self.navigationItem.rightBarButtonItem = nil;   

 

}   

 

- (void)leaveEditMode {   

 

    [self.textView resignFirstResponder];   

 

}   

 

 

 

(2)如果你的textview里不用回车键,可以把回车键当做退出键盘的响应键。

代码如下:

 

#pragma mark - UITextView Delegate Methods   

 

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text   

 

{   

 

    if ([text isEqualToString:@"\n"]) {   

 

        [textView resignFirstResponder];   

 

        return NO;   

 

    }   

 

    return YES;   

 

}   

 

 

 

 

这样无论你是使用电脑键盘上的回车键还是使用弹出键盘里的return键都可以达到退出键盘的效果。

(3)还有你也可以自定义其他加载键盘上面用来退出,比如在弹出的键盘上面加一个view来放置退出键盘的Done按钮。

代码如下:

 

 

UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];   

 

    [topView setBarStyle:UIBarStyleBlack];   

 

    UIBarButtonItem * helloButton = [[UIBarButtonItem alloc]initWithTitle:@"Hello" style:UIBarButtonItemStyleBordered target:self action:nil];         

 

    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];   

 

       

 

    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];   

 

    NSArray * buttonsArray = [NSArray arrayWithObjects:helloButton,btnSpace,doneButton,nil];   

 

    [doneButton release];   

 

    [btnSpace release];   

 

    [helloButton release];   

 

    [topView setItems:buttonsArray];   

 

    [tvTextView setInputAccessoryView:topView];   

 

-(IBAction)dismissKeyBoard   

 

{   

 

    [tvTextView resignFirstResponder];   

 

}   

 

(4)设置UITextView圆角问题

做法是在#import QuartzCore/QuartzCore.h 后,便能調用[textView.layer setCornerRadius:10]; 來把UITextView 设定圓角

(5)UITextView根据文本大小自适应高度

通过实现文本字数来确定高度,如下:

 

 

NSString * desc = @"Description it is  a test font, and don't become angry for which i use to do here.Now here is a very nice party from american or not!";   

 

CGSize  size = [desc sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(240, 2000) lineBreakMode:UILineBreakModeWordWrap];  

 

 

 

只有UILabel需要定义的numberoflines为0,即不做行数的限制。如下:

 

[label  setNumberOfLines:0];   

[label  setFrame:CGRectMake(40, 135, 240, size.height+10)];   

[label setText:desc];  

 

 

 

 

 

 

(6)UITextView自定选择文字后的菜单

在ViewDidLoad中加入:

 

UIMenuItem *menuItem = [[UIMenuItem alloc]initWithTitle:@"分享到新浪微博" action:@selector(changeColor:)]; 

UIMenuController *menu = [UIMenuController sharedMenuController]; 

[menu setMenuItems:[NSArray arrayWithObject:menuItem]]; 

[menuItem release]; 

 

 

当然上面那个@selector里面的changeColor方法还是自己写吧,也就是说点击了我们自定义的菜单项后会触发的方法。

然后还得在代码里加上一个方法:

 

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender 

if(action ==@selector(changeColor:)) 

if(textView.selectedRange.length>0) 

return YES; 

return NO; 

 

今天的UITextView就讲到这里,主要讲了UITextView的初始化和开发中会遇到的一些问题和自定义等问题。谢谢大家支持哈。

posted @ 2012-01-31 19:09 SuperHappy 阅读(66) 评论(0) 编辑

UILabel的常见用法

- (void)loadView
{
    [super loadView];    //1.UILable的大小自适应实例:    UILabel *myLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 2, 2)];//设定位置与大小    [myLabel setFont:[UIFont fontWithName:@"Helvetica" size:20.0]];//格式    [myLabel setNumberOfLines:0];//行数,只有设为0才可以自适应    [myLabel setBackgroundColor:[UIColor clearColor]];//背景色    myLabel.shadowColor = [UIColor darkGrayColor];//阴影颜色    myLabel.shadowOffset = CGSizeMake(1.0,1.0);//阴影大小    
    NSString *text = @"abcdefghigklmnopqrstuvwxyz";
    UIFont *font = [UIFont fontWithName:@"Helvetica" size:20.0];
    CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(175.0f, 2000.0f) lineBreakMode:UILineBreakModeWordWrap];
    CGRect rect=myLabel.frame;
    rect.size=size;
    [myLabel setFrame:rect];
    [myLabel setText:text];
     myLabel.shadowColor = [UIColor darkGrayColor];//阴影颜色     myLabel.shadowOffset = CGSizeMake(2.0,2.0);//阴影大小    [self.view addSubview:myLabel];
    [myLabel release];    //2.UILable的基本用法获取自馒头MAN百度空间,感谢馒头MAN            //空间地址:http://hi.baidu.com/bunsman/blog/item/95777b0ebacf05fe36d122e2.html    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 40.0, 200.0, 30.0)];     
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 80.0, 200.0, 50.0)];     
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 140.0, 200.0, 50.0)];     
    UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 200.0, 200.0, 50.0)];     
    UILabel *label5 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 260.0, 200.0, 50.0)];     
    UILabel *label6 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 320.0, 200.0, 50.0)];     
    UILabel *label7 = [[UILabel alloc]initWithFrame:CGRectMake(50.0, 380.0, 200.0, 50.0)];     
    
    //设置显示文字         label1.text = @"label1";     
    label2.text = @"label2";     
    label3.text = @"label3--label3--label3--label3--label3--label3--label3--label3--label3--label3--label3--11个";     
    label4.text = @"label4--label4--label4--label4--4个";     
    label5.text = @"label5--label5--label5--label5--label5--label5--6个";     
    label6.text = @"label6";     
    label7.text = @"label7";     
    
    //设置字体:粗体,正常的是 SystemFontOfSize         label1.font = [UIFont boldSystemFontOfSize:20];     
    
    //设置文字颜色      label1.textColor = [UIColor orangeColor];     
    label2.textColor = [UIColor purpleColor];     
    //设置背景颜色     label1.backgroundColor = [UIColor clearColor];
    label2.backgroundColor = [UIColor  colorWithRed:0.5f green:30/255.0f blue:0.3f alpha:0.5f];    //设置文字位置         label1.textAlignment = UITextAlignmentRight;     
    label2.textAlignment = UITextAlignmentCenter;     
    //设置字体大小适应label宽度         label4.adjustsFontSizeToFitWidth = YES;    //设置label的行数         label5.numberOfLines = 2;     
    
    //设置高亮         label6.highlighted = YES;     
    label6.highlightedTextColor = [UIColor orangeColor];     
    
    //设置阴影         label7.shadowColor = [UIColor redColor];     
    label7.shadowOffset = CGSizeMake(1.0,1.0);     
    
    //设置是否能与用户进行交互         
    label7.userInteractionEnabled = YES;     
    
    //设置label中的文字是否可变,默认值是YES         label3.enabled = NO;     
    
    //设置文字过长时的显示格式         
    label3.lineBreakMode = UILineBreakModeMiddleTruncation;//截去中间     
    //  typedef enum {     
    //      UILineBreakModeWordWrap = 0,     
    //      UILineBreakModeCharacterWrap,     
    //      UILineBreakModeClip,//截去多余部分     
    //      UILineBreakModeHeadTruncation,//截去头部     
    //      UILineBreakModeTailTruncation,//截去尾部     
    //      UILineBreakModeMiddleTruncation,//截去中间     
    //  } UILineBreakMode;     
    
    //如果adjustsFontSizeToFitWidth属性设置为YES,这个属性就来控制文本基线的行为         label4.baselineAdjustment = UIBaselineAdjustmentNone;     
    //  typedef enum {     
    //      UIBaselineAdjustmentAlignBaselines,     
    //      UIBaselineAdjustmentAlignCenters,     
    //      UIBaselineAdjustmentNone,     
    //  } UIBaselineAdjustment;         
    
    [self.view addSubview:label1];     
    [self.view addSubview:label2];     
    [self.view addSubview:label3];     
    [self.view addSubview:label4];     
    [self.view addSubview:label5];     
    [self.view addSubview:label6];     
    [self.view addSubview:label7];     
    
    [label1 release];     
    [label2 release];     
    [label3 release];     
    [label4 release];     
    [label5 release];     
    [label6 release];     
    [label7 release];         
    
}

posted @ 2012-01-31 18:50 SuperHappy 阅读(212) 评论(0) 编辑

窗口,视图,视图控制器和UIKit基础

1、窗口:UIWindow

iPhone的规则是一个窗口,多个视图,窗口是你在app显示出来你看到的最底层,他是固定不变的,基本上可以不怎么理会,但要知道每层是怎样的架构。

2、视图:UIView

UIView是用户构建界面的基础,所有的控件都是在这个页面上画出来的,你可以把它当成是一个画布,你可以通过UIView增加控件,并利用控件和用户进行交互和传递数据。

窗口和视图是最基本的类,创建任何类型的用户界面都要用到。窗口表示屏幕上的一个几何区域,而视图类则用其自身的功能画出不同的控件,如导航栏,按钮都是附着视图类之上的,而一个视图则链接到一个窗口。

3、视图控制器:UIViewController

视图控制器UIViewController,你可以把他当成是对你要用到视图UIView进行管理和控制,你可以在这个UIViewController控制你要显示的是哪个具体的UIView。另外,视图控制器还增添了额外的功能,比如内建的旋转屏幕,转场动画以及对触摸等事件的支持。

4、  UIKit简介

(1)显示数据的视图

UITextView:将文本段落呈现给用户,并允许用户使用键盘输入自己的文本。

 

UILabel:实现短的只读文本,可以通过设置视图属性为标签选择颜色,字体和字号等。

UIImageView:可以通过UIImage加载图片赋给UIImageView,加载后你可以指定显示的位置和大小。

 

UIWebView:可以提供显示HTML.PDF等其他高级的Web内容。包括xls,word等文档等。

 

MKMapView:可以通过MKMapView向应用嵌入地图。很热门的LBS应用就是基于这个来做的。还可以结合MKAnnotationView和MKPinAnnotationView类自定义注释信息注释地图。


 

UIScrollView:一般用来呈现比正常的程序窗口大的一些内容。可以通过水平和竖直滚动来查看全部的内容,并且支持缩放功能。

(2) 做出选择的视图

UIAlertView:通过警告视图让用户选择或者向用户显示文本。

 

UIActionSheet:类似UIAlertView,但当选项比较多的时候可以操作表单,它提供从屏幕底部向上滚动的菜单。

 

(3)其他

UIBuuton:主要是我们平常触摸的按钮,触发时可以调用我们想要执行的方法。

 

UISegmentControl:选择按钮,可以设置多个选择项,触发相应的项调用不同的方法。

 

UISwitch:开关按钮,可以选择开或者关。

UISlideer:滑动按钮,常用在控制音量等。

 

 

UITextField:显示文本段,显示所给的文本。

UITableView:表格视图,可以定义你要的表格视图,表格头和表格行都可以自定义,自定义的一个表格如下图:

 

UIPickerView:选择条,一般用于日期的选择。

 

UISearchBar:搜索条,一般用于查找的功能。

 

UIToolBar:工具栏:一般用于主页面的框架。

 

UIActivityIndicatorView:进度条,一般用于显示下载进度。

UIProgressView:进度条,一般用于显示下载的进度条。

 

 

今天就简单的介绍了一下IOS应用开发常用的一些控件,还有基础的UIView,UIWindow和UIViewControl之间的关系,这些是基础,直接影响到以后开发的能力,接下来我将分开讲这些控件。


对于Button的圆角显示,利用layer实现

示例:

对button1的边框进行设置

#import <QuartzCore/QuartzCore.h>//不要忘记添加库文件

CALayer *layer1=[button1 layer];

    //是否设置边框以及是否可见

    [layer1 setMasksToBounds:YES];

    //设置边框圆角的弧度

    [layer1 setCornerRadius:15.0];

    //设置边框线的宽

    [layer1 setBorderWidth:2.0];

    //设置边框线的颜色

    [layer1 setBorderColor:[[UIColorgrayColor] CGColor]];

posted @ 2012-01-31 15:52 SuperHappy 阅读(48) 评论(0) 编辑

NSNotificationCenter

新建一个继承于UIViewControll的类,并在.m中添加如下代码

-(void)doSomeThing:(NSNotification *)aNote
{
    NSDictionary *dict = [aNote object];
    NSLog(@"%@",dict);
}
- (void)loadView
{
    [super loadView];
    NSString *myString = @"some Value";
    NSDictionary *myDict = [[NSDictionary alloc]initWithObjectsAndKeys:myString,@"first", nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];
    
}

设置通知:

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(doSomeThing:) name:@"notification" object:nil];

addObserver 这个是观察者,就是说 在什么地方接收通知;

 selector 这个是收到通知后,调用何种方法;

 name: 这个是通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

   object:  对象,当设定为nil时,默认为所有名称为以上消息名称的(notification)都接收不管发送者是谁。

发送通知:

[[NSNotificationCenter defaultCenter]postNotificationName:@"notification" object:myDict];

postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

object:对象,当设定为nil时,默认为所有名称为以上消息名称的(notification)都发送。

小例子仅仅是在一个类下的通知,实际来说通知更多的应用于不同的类之间传递信息。

posted @ 2012-01-31 15:38 SuperHappy 阅读(57) 评论(0) 编辑

简单的大头针地图标示练习(无xib)

用4.2创建的空模班,添加的UIViewController类,取名为mapView.(按正规命名方式应该为MapView,大家见谅)。

以下为添加的代码

mapView.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import <QuartzCore/QuartzCore.h>

@interface mapView : UIViewController <CLLocationManagerDelegate>
{
    CLLocationManager *locManager;
    MKMapView *map;
    CLLocation *bestLocation;
}
@property (retain) CLLocationManager *locManager;
@property (retain) CLLocation *bestLocation;
@end

 mapView.m

  mapView.m//  Map  Created by SuperHappy on 12-1-31.//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.//#import "mapView.h"#define BARBUTTON(TITLE, SELECTOR)     [[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR] autorelease]@implementation mapView@synthesize locManager;@synthesize bestLocation;

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"Location manager error :%@",[error description]);
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{    if (!self.bestLocation) {
        self.bestLocation = newLocation;
    }    else if(newLocation.horizontalAccuracy < bestLocation.horizontalAccuracy)
        self.bestLocation = newLocation;
    map.region = MKCoordinateRegionMake(self.bestLocation.coordinate, MKCoordinateSpanMake(0.1f, 0.1f));
    map.showsUserLocation = YES;
    map.zoomEnabled = NO;

}
- (void)findme
{    // disable right button    self.navigationItem.rightBarButtonItem = nil;    
    // Search for the best location
    self.bestLocation = nil;
    self.locManager.delegate = self;
    [self.locManager startUpdatingLocation];}

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

- (void)didReceiveMemoryWarning
{    // Releases the view if it doesn't have a superview.    [super didReceiveMemoryWarning];    
    // Release any cached data, p_w_picpaths, etc that aren't in use.}#pragma mark - View lifecycle// Implement loadView to create a view hierarchy programmatically, without using a nib.- (void)loadView
{
    [super loadView];
    map = [[MKMapView alloc]initWithFrame:CGRectMake(10, 10, 300, 300)];
    [self.view addSubview:map];
    [map release];
    
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
    
    self.locManager = [[[CLLocationManager alloc] init] autorelease];    if (!self.locManager.locationServicesEnabled)
    {
        NSLog(@"User has opted out of location services");        return;
    }    else 
    {        // User generally allows location calls        self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.navigationItem.rightBarButtonItem = BARBUTTON(@"Find Me", @selector(findme));
    }

}/*// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}*/- (void)viewDidUnload
{
    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{    // Return YES for supported orientations    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}@end