UILabel、UITextField、UIButton、UIImageView控件


四大美女大笑,,走起!!!偷笑偷笑

//一、UIlabel標籤控件


 //1.開闢空間並初始化

    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];

  //2.設置屬性

    

    //1)背景顏色

    [label setBackgroundColor:[UIColor magentaColor]];

    

    //2)標題

    [label setText:@"我一直都在rrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"];

    

   //3)字體加粗及大小

    [label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:18]];

        //採用系統默認文字大小設置大小

        //label setFont:[UIFont systemFontOfSize:12];

    //4)標題位置

         //標題居中

        [label setTextAlignment:NSTextAlignmentCenter];

        //向左對齊

        [label setTextAlignment:NSTextAlignmentLeft];

    //5)設置文本行數

      //顯示文本行數(限定行數),不設置時系統會默認行數爲1

       //當需要設置的行數爲不限制數量的時候可以用numberOflines=0實現

    //[label setNumberOfLines:2];

        //設置文本多行顯示

       //[label setLineBreakMode:NSLineBreakByWordWrapping];

       [label setNumberOfLines:0];

    

    //6)字體陰影顏色

    [label setShadowColor:[UIColor yellowColor]];

    

  //7)陰影大小(陰影向X正方向偏移2,向y方向偏移1

    [label setShadowOffset:CGSizeMake(2, 1)];

    

    //8)設置label的邊框顏色

    label.layer.borderColor=[UIColor blueColor].CGColor;

    

    //9)設置label的邊框寬度

    label.layer.borderWidth=1;

    

    //10)設置label圓角

    label.layer.cornerRadius=10;

  //3.添加到視圖

    [self.view addSubview:label];

    

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. label.tag =101;   

其中textAlignment有三種設置方式:NSTextAlignmentLeft爲向左對齊,NSTextAlignmentCenter爲居中對齊,NSTextAlignmentRight爲向右對齊

如果有一些文章介紹時用的是UITextAlignmentCenter/UITextAlignmentLeft/UITextAlignmentRight,那是iOS6以前的用法,iOS6的最新用法已改

當文本內容很多,label無法全部顯示時label會將文本內容以省略號的方式代替,下面說一下label文本省略方式的設置

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. label.lineBreakMode =NSLineBreakByCharWrapping;//其中lineBreakMode可選值爲  
  2. linBreakMode enum{  
  3. NSLineBreakByWordWrapping = 0,//保留整個單詞,以空格爲邊界  
  4.    NSLineBreakByCharWrapping,//保留整個字符  
  5.    NSLineBreakByClipping,//以邊界爲止  
  6.    NSLineBreakByTruncatingHead,//省略開頭,以省略號代替  
  7.    NSLineBreakByTruncatingTail,//省略結尾,以省略號代替  
  8.    NSLineBreakByTruncatingMiddle//省略中間,以省略號代替  
  9.    }  

當label大小使用sizeToFit方法,調整大小時會考慮到該屬性中存儲的值。例如,如果此屬性設置爲3,sizeToFit方法會調整label使它大到足以顯示三行文本。
[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. [label sizeToFit];  
文本自動根據label大小自動調整字體尺寸

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. label.numberOfLines =1;  
  2. label.adjustsFontSizeToFitWidth =YES;  
adjustFontSizeToFitWidth方法可實現文本自動根據label大小自動調整字體尺寸,直到文本的大小達到了自己設置的label文本尺寸最大、最小值與字符串的最大最小值,要是用這個方法還有一個很大的限制就是只有在numberOfLines設置爲1時才能用


如果行數是超過了1行,要實現自動調整字體大小功能,就沒有可以自適應的系統方法可以使用,只有自己用代碼實現,在設計時因爲要考慮到手機屏幕的實際大小有限,如果字體太小會影響用戶體驗,所以要設置一個最小字號的判斷,小於最小字號就要用到縮略顯示,下面的代碼中主要是用到
[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(100180) lineBreakMode:NSLineBreakByCharWrapping];  

來得到字體在某一字號下的高度,判斷與label高度是否一致,其中text是輸入label的文本內容,sizWithFont設置字體,constrainedToSize設置約束文本的矩形大小參數,其中寬度要和label一致,高度設置要足夠高,要比label高很多,否則會出現文本顯示不全的問題,lineBreakMode的作用上文有講過。如果算出的高度超出了label高度,就把字號以循環的方式減小直到高度符合就跳出循環。

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. float maxHeight =50;//設置最大高度  
  2.     float minFontSize =9;  
  3.     float height;  
  4.     int fontSize = 31;//設置最大字號  
  5.     NSString *text = @"輸入文本內容";  
  6.     do {  
  7.         fontSize = fontSize - 1;  
  8.             UIFont *font =[UIFont fontWithName:@"Arial" size:fontSize];  
  9.             CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(100180)/*寬度與label的寬度一樣,高度應高於label高度*/ lineBreakMode:NSLineBreakByCharWrapping];  
  10.         height = size.height;  
  11.         NSLog(@"height=%f,fontSize=%d,text=%@",height,fontSize,text);  
  12.     } while (height > maxHeight&&fontSize>minFontSize);  
  13.   
  14.     UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(505010050)];  
  15.     label.text =text;  
  16.     if (fontSize ==9) {//判斷字體是否小於最小字號,小於最小字號時就使用系統默認的縮略顯示  
  17.         label.font = [UIFont fontWithName:@"Arial" size:15];  
  18.     }  
  19.     else{  
  20.     label.font = [UIFont fontWithName:@"Arial" size:fontSize];  
  21.     label.lineBreakMode = NSLineBreakByCharWrapping;//實現文字多行顯示  
  22.     label.numberOfLines = 0;  
  23.     }  
  24.     [self.view addSubview:label];  
根據文本數量自動調整label高度
其實就是用上面的方法得到高度再生成label

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. NSString *text =[[NSString alloc]init];  
  2.   text = @"輸入文本內容";  
  3.   CGSize size = CGSizeMake(280180);  
  4.   UIFont *fonts = [UIFont systemFontOfSize:14.0];  
  5.   CGSize msgSie = [text sizeWithFont:fonts constrainedToSize:size lineBreakMode: NSLineBreakByCharWrapping];  
  6.   UILabel *textLabel  = [[UILabel alloc] init];  
  7.   [textLabel setFont:[UIFont boldSystemFontOfSize:14]];  
  8.   textLabel.frame = CGRectMake(20,70280,msgSie.height);  
  9.   textLabel.text = text;  
  10.   textLabel.lineBreakMode = NSLineBreakByCharWrapping;//實現文字多行顯示  
  11.   textLabel.numberOfLines = 0;  
  12.   [self.view addSubview:textLabel];  
設置label背景圖
設置背景圖有兩種方法,下面先介紹第一種方法:
設置背景圖可以把一張大小與label一樣的圖放在label的後面一層,然後把label的背景設置爲透明,這樣實現label有背景

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(5050200400)];  
  2. UIImageView *imageView =[[UIImageView alloc]init];  
  3. imageView.frame =CGRectMake(5050200400);  
  4. UIImage *image=[UIImage imageNamed:@"1.jpg"];  
  5. imageView.image =image;//imageView會根據自身大小改變添加的圖片的大小所以不需要額外設置image  
  6. label.backgroundColor = [UIColor clearColor];  
  7. label.text =@"hello world";  
  8. label.font = [UIFont systemFontOfSize:30];  
  9. label.textColor = [UIColor yellowColor];  
  10. [self.view addSubview:imageView];//添加的順序不能錯,否則圖片會覆蓋label  
  11. [self.view addSubview:label];  
這個是一個有點不正統的方法,下面要介紹更加規範的第二種方法:用UIColor設置圖片,然後把UIColor作爲背景顏色,就可以實現label設置背景圖

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. UIColor * color = [UIColor colorWithPatternImage:image];//image爲需要添加的背景圖  
  2.  UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(5050100200)];  
  3.  [label setBackgroundColor:color];  
  4.  [self.view addSubview:label];  
但這個方法有一個嚴重的缺陷,就是當背景圖的尺寸與label大小不一致時,會出現背景圖被部分截取或者平鋪重複的情況,所以更完善的方法是要先修改好背景圖的大小與label大小一致再設置背景顏色。可以用下面的函數設置image尺寸

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. -(UIImage *)scaleImage:(UIImage *)img ToSize:(CGSize)itemSize{  
  2.     UIImage *i;  
  3.     // 創建一個bitmap的context,並把它設置成爲當前正在使用的context  
  4.     UIGraphicsBeginImageContext(itemSize);  
  5.     CGRect imageRect=CGRectMake(00, itemSize.width, itemSize.height);  
  6.     // 繪製改變大小的圖片  
  7.     [img drawInRect:imageRect];  
  8.     // 從當前context中創建一個改變大小後的圖片  
  9.     i=UIGraphicsGetImageFromCurrentImageContext();  
  10.     // 使當前的context出堆棧  
  11.     UIGraphicsEndImageContext();  
  12.     // 返回新的改變大小後的圖片  
  13.     return i;  
  14. }  
然後在主函數中調用即可

[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. CGSize size= CGSizeMake(100200);  
  2.     UIImage *image =[UIImage imageNamed:@"1.jpg"];  
  3.     UIImage *laterImage =[self scaleImage:image ToSize:size];  
  4.     UIColor * color = [UIColor colorWithPatternImage:laterImage];  
  5.    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(5050100200)];  
  6.    [label setBackgroundColor:color];  
  7.    [self.view addSubview:label];  



二、UITextField (輸入框)


  //使用初始化創建對象

   UITextField * field=[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 100, 50)];

    [field setBackgroundColor:[UIColor cyanColor]];

    //設置邊框風格

    field.borderStyle=UITextBorderStyleRoundedRect;

    //設置佔位符

    field.placeholder=@"請輸入賬號";

    //彈出鍵盤

                //數字鍵盤

//    [file setKeyboardType:UIKeyboardTypeDecimalPad];

      // 谷歌鍵盤

  //  [file setKeyboardType:UIReturnKeyGoogle];

  

//鍵盤右下角return按鍵類型(枚舉值)

  field returnKeyType=UIReturnKeyGoogel;


    //重置(總是顯示清除按鈕)

    [field setClearButtonMode:UITextFieldViewModeAlways];

  //密碼安全性(以點顯示)

    field.secureTextEntry=YES;


    [self.view addSubview:field];

    [field setDelegate:self];


//使用UITextFieldDelegate來隱藏鍵盤 
//在iPhone界面上,時常會需要當用戶輸入完內容後,隱藏鍵盤。 當然有很多方法,今天只介紹使用UITextFieldDelegate這個協議實現隱藏鍵盤。

1. 在你的控制器類中,加入UITextFieldDelegate這個協議
如:@interface AddItemViewController : UIViewController <UITextFieldDelegate>
2. 在使用了UITextFieldDelegate協議的控制器類的實現中,加入- (BOOL)textFieldShouldReturn:方法。
- (BOOL)textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];
return YES;
}


//如何限制文本框只能輸入數字:
//建立NSNumberFormatter的子類,增加這個方法,將formatter鏈接至文本框。

- (BOOL) isPartialStringValid: (NSString **) partialStringPtr
proposedSelectedRange: (NSRangePointer) proposedSelRangePtr
originalString: (NSString *) origString
originalSelectedRange: (NSRange) origSelRange
errorDescription: (NSString **) error
{
NSCharacterSet *nonDigits;
NSRange newStuff;
NSString *newStuffString;

nonDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
newStuff = NSMakeRange(origSelRange.location,
proposedSelRangePtr->location
- origSelRange.location);
newStuffString = [*partialStringPtr substringWithRange: newStuff];

if ([newStuffString rangeOfCharacterFromSet: nonDigits
options: NSLiteralSearch].location != NSNotFound) {
*error = @"不是數字";
return (NO);
} else {
*error = nil;
return (YES);
}

}

    

//點擊 UITextView 輸入文字,光標都從最初點開始
- (void)textViewDidChangeSelection:(UITextView *)textView
{
NSRange range;
range.location = 0;
range.length = 0;
textView.selectedRange = range;
}

//限制輸入文本的長度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (range.location >= MAX_LENGTH)
return NO; // return NO to not change text
return YES;
}
if (textField.text.length >= 10 && range.length == 0)
return NO;
return YES;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([textField.text length] > MAXLENGTH)
{
textField.text = [textField.text substringToIndex:MAXLENGTH-1];
return NO;
}
return YES;
}


三、UIButton (按鈕)

 //便利構造器方法創建對象

UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];

    [button setFrame:CGRectMake(100, 200, 100, 100)];

    

  //button的背景顏色

    //[button setBackgroundColor:[UIColor yellowColor]];

    

 // 設置button的標題

    [button setTitle:@"登錄" forState:UIControlStateNormal];

    

 // 設置button標題的顏色

    [button setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal];

    

 //  設置按鈕按下會發光

    [button setShowsTouchWhenHighlighted:YES];

    

 //點擊事件(button control

       //Target_action目標——動作模式,在兩個對象間直接發送消息  self指的是當前對象   點擊它後,它指定了一個target(目標對象),並執行目標對象上指定的action(方法:click點擊)。

  //添加點擊事件

    [button addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

    

    //設置按鈕的背景圖片

    [button setBackgroundImage:[UIImage imageNamed:@"4.jpg"] forState:UIControlStateNormal];

    [self.view addSubview:button];

    

    

}

//實現點擊事件方法

-(void)click{

    

}

  //四、UIImageView (圖片)

    //初始化

    UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 350)];

    //直接顯示圖片

   // [imageView setImage:[UIImage imageNamed:@"4.jpg"]];

    

    //通過路勁顯示圖片

    NSString *path=[[NSBundle mainBundle]pathForResource:@"3" ofType:@"jpg"];

    [imageView setImage:[UIImage imageWithContentsOfFile:path]];

    

    //設置圓角

    imageView.layer.masksToBounds=YES;

    imageView.layer.cornerRadius=10;

    

    //設置邊框顏色和大小

    imageView.layer.borderColor=[UIColor yellowColor].CGColor;

    imageView.layer.borderWidth=3;

    

    

    [self.view addSubview:imageView];

//自動播放一系列圖片

    //1.圖片添加到組

    UIImage *image1=[UIImage imageNamed:@"1.jpg"];

    UIImage *image2=[UIImage imageNamed:@"2.jpg"];

    UIImage *image3=[UIImage imageNamed:@"3.jpg"];

    UIImage *image4=[UIImage imageNamed:@"4.jpg"];

    UIImage *image5=[UIImage imageNamed:@"5.jpg"];

    NSArray *imageArray=@[image1,image2,image3,image4,image5];

//用for循環的方式把圖片放入數組

//    NSMutableArray *imageArray=[[NSMutableArray alloc]init];

//    for (int i=0; i<5; i++) {

//        NSString *filename=[NSString stringWithFormat:@"%d.jpg",i];

 

/*

//另一種獲取圖片路徑方法

// NSString *path=[NSString stringWithFormat:@"%ld.jpg",a++];

            [image setImage:[UIImage imageNamed:path]];

       */

//        NSString *path=[[NSBundle mainBundle]pathForResource:filename ofType:nil];

//        UIImage *image=[UIImage imageWithContentsOfFile:path];

//        [imageArray addObject:image];

    //2.設置一組動態圖

    imageView.animationImages=imageArray;

    //3.設定播放一組動態圖片的時間

    imageView.animationDuration=[imageArray count];

    //4.設置重複次數(0表示無數次)

    imageView.animationRepeatCount=0;

    //5.開始播放

    [imageView startAnimating];

    

    

    //爲圖片添加單擊事件:一定要先將userInteractionEnabled置爲YES,這樣才能響應單擊事件

    imageView.userInteractionEnabled = YES;

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizerallocinitWithTarget:self action:@selector(tapImageView:)];

    [imageView addGestureRecognizer:singleTap];

    

    // 隱藏或者顯示圖片

//    imageView.hidden = YES或者NO; 

 // 設置透明度  

    imageView.alpha =0.5;   

    // 設置高亮時顯示的圖片

    //imageView.highlightedImage = (UIImage *)hightlightedImage;

    // 設置正常顯示的圖片

     //imageView.image = (UIImage *)image;

*******注意注意:疑問   疑問

//需要設置圖片 UIImage

第一種:[imageView setImage:[UIImage imageNamed:@"1.jpeg"]];

//第二種:
NSString *filePath=[[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpeg"];
UIImage *images=[UIImage imageWithContentsOfFile:filePath];
//[imageView setImage:images]; 

//第三種:
NSData *data=[NSData dataWithContentsOfFile:filePath];
UIImage *image2=[UIImage imageWithData:data];
[imageView setImage:image2];


其中第一 二種屬於一種,共兩種:

1)用imageNamed的方式加載時,系統會把圖像Cache到內存。如果圖像比較大,或者圖像比較多,用這種方式會消耗很大的內存,而且釋放圖像的內存是一件相對來說比較麻煩的事情。例如:如果利用imageNamed的方式加載圖像到一個動態數組NSMutableArray,然後將將數組賦予一個UIView的對象的animationImages進行逐幀動畫,那麼這將會很有可能造成內存泄露。並且釋放圖像所佔據的內存也不會那麼簡單。但是利用imageNamed加載圖像也有自己的優勢。對於同一個圖像系統只會把它Cache到內存一次,這對於圖像的重複利用是非常有優勢的。例如:你需要在一個TableView裏重複加載同樣一個圖標,那麼用imageNamed加載圖像,系統會把那個圖標Cache到內存,在Table裏每次利用那個圖像的時候,只會把圖片指針指向同一塊內存。這種情況使用imageNamed加載圖像就會變得非常有效。

    2)利用NSData方式加載時,圖像會被系統以數據方式加載到程序。當你不需要重用該圖像,或者你需要將圖像以數據方式存儲到數據庫,又或者你要通過網絡下載一個很大的圖像時,請儘量使用imageWithData的方式加載圖像。

    無論用哪種方式加載圖像,圖像使用結束後,一定要記得顯示釋放內存。    



    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章