iOS基础之OC简单控件知识了解(二)

一.UITextField属性

0.        enablesReturnKeyAutomatically

默认为No,如果设置为Yes,文本框中没有输入任何字符的话,右下角的返回按钮是disabled的。

1.borderStyle

设置边框样式,只有设置了才会显示边框样式 

  text.borderStyle =UITextBorderStyleRoundedRect;

 typedef enum {

    UITextBorderStyleNone, 

    UITextBorderStyleLine,

    UITextBorderStyleBezel,

    UITextBorderStyleRoundedRect 

  }UITextBorderStyle;                                                      

 

2.backgroundColor 

设置输入框的背景颜色,此时设置为白色 如果使用了自定义的背景图片边框会被忽略掉 

  text.backgroundColor =[UIColor whiteColor];

3.background

设置背景

  text.background = [UIImageimageNamed:@"dd.png"];//UITextField 的背景,注意只有UITextBorderStyleNone的时候改属性有效

 

设置enable为no时,textfield的背景 

  text.disabledBackground = [UIImageimageNamed:@"cc.png"];

 

4.placeholder

当输入框没有内容时, 提示内容为password

  text.placeholder =@"password";

5.font

设置输入框内容的字体样式和大小

  text.font = [UIFontfontWithName:@"Arial" size:20.0f];

6. textColor

设置字体颜色

  text.textColor = [UIColor redColor];

7. clearButtonMode

输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容

  text.clearButtonMode = UITextFieldViewModeAlways; 

typedef enum {

    UITextFieldViewModeNever, 重不出现

   UITextFieldViewModeWhileEditing, 编辑时出现

   UITextFieldViewModeUnlessEditing, 除了编辑外都出现

    UITextFieldViewModeAlways  一直出现

} UITextFieldViewMode;

 

8. text

输入框中一开始就有的文字

  text.text = @"一开始就在输入框的文字";

9. secureTextEntry

每输入一个字符就变成点 用来输入密码时,设置这个属性。

  text.secureTextEntry = YES;

10. autocorrectionType

是否纠错

  text.autocorrectionType =UITextAutocorrectionTypeNo;

typedef enum {

   UITextAutocorrectionTypeDefault, 默认

    UITextAutocorrectionTypeNo,  不自动纠错

    UITextAutocorrectionTypeYes, 自动纠错

} UITextAutocorrectionType;

 

11. clearsOnBeginEditing

再次编辑就清空

  text.clearsOnBeginEditing = YES; 

12. textAlignment

内容对齐方式

  text.textAlignment =UITextAlignmentLeft;

13. contentVerticalAlignment

内容的垂直对齐方式  UITextField继承自UIControl,此类中有一个属性contentVerticalAlignment

  text.contentVerticalAlignment =UIControlContentVerticalAlignmentCenter;

14. adjustsFontSizeToFitWidth

设置为YES时文本会自动缩小以适应文本窗口大小.默认是保持原来大小,而让长文本滚动 

  textFied.adjustsFontSizeToFitWidth =YES;

//设置自动缩小显示的最小字体大小

  text.minimumFontSize = 20;

 

15. keyboardType

设置键盘的样式

  text.keyboardType =UIKeyboardTypeNumberPad;

typedef enum {

    UIKeyboardTypeDefault,     默认键盘,支持所有字符         

    UIKeyboardTypeASCIICapable, 支持ASCII的默认键盘

   UIKeyboardTypeNumbersAndPunctuation, 标准电话键盘,支持+*#字符

    UIKeyboardTypeURL,           URL键盘,支持.com按钮 只支持URL字符

UIKeyboardTypeNumberPad,            数字键盘

UIKeyboardTypePhonePad,   电话键盘

    UIKeyboardTypeNamePhonePad,  电话键盘,也支持输入人名

UIKeyboardTypeEmailAddress,  用于输入电子 邮件地址的键盘    

UIKeyboardTypeDecimalPad,    数字键盘 有数字和小数点

    UIKeyboardTypeTwitter,      优化的键盘,方便输入@、#字符

    UIKeyboardTypeAlphabet =UIKeyboardTypeASCIICapable, 

} UIKeyboardType;

16.autocapitalizationType

首字母是否大写

  text.autocapitalizationType =UITextAutocapitalizationTypeNone;

typedef enum {

   UITextAutocapitalizationTypeNone, 不自动大写

   UITextAutocapitalizationTypeWords, 单词首字母大写

   UITextAutocapitalizationTypeSentences, 句子的首字母大写

   UITextAutocapitalizationTypeAllCharacters, 所有字母都大写

} UITextAutocapitalizationType;

17. returnKeyType

return键变成什么键

 text.returnKeyType =UIReturnKeyDone;

typedef enum {

    UIReturnKeyDefault, 默认 灰色按钮,标有Return

    UIReturnKeyGo,     标有Go的蓝色按钮

    UIReturnKeyGoogle,标有Google的蓝色按钮,用语搜索

    UIReturnKeyJoin,标有Join的蓝色按钮

    UIReturnKeyNext,标有Next的蓝色按钮

    UIReturnKeyRoute,标有Route的蓝色按钮

    UIReturnKeySearch,标有Search的蓝色按钮

    UIReturnKeySend,标有Send的蓝色按钮

    UIReturnKeyYahoo,标有Yahoo的蓝色按钮

    UIReturnKeyYahoo,标有Yahoo的蓝色按钮

    UIReturnKeyEmergencyCall, 紧急呼叫按钮

} UIReturnKeyType;

18. keyboardAppearance

键盘外观

textView.keyboardAppearance=UIKeyboardAppearanceDefault;

typedef enum {

UIKeyboardAppearanceDefault, 默认外观,浅灰色

UIKeyboardAppearanceAlert,   深灰 石墨色

} UIReturnKeyType;

 

 19. delegate

设置代理 用于实现协议

  text.delegate = self;

 

20.  rightView

最右侧加图片是以下代码  左侧类似

    UIImageView*image=[[UIImageView alloc] initWithImage:[UIImageimageNamed:@"right.png"]];

    text.rightView=image;

    text.rightViewMode =UITextFieldViewModeAlways; 

typedef enum {

    UITextFieldViewModeNever,

    UITextFieldViewModeWhileEditing,

   UITextFieldViewModeUnlessEditing,

    UITextFieldViewModeAlways

} UITextFieldViewMode;

 

21.editing

是否允许编辑。

 

22.界面重写绘制行为

除了UITextField对象的风格选项,你还可以定制化UITextField对象,为他添加许多不同的重写方法,来改变文本字段的显示行为。这些方法都会返回一个CGRect结构,制定了文本字段每个部件的边界范围。以下方法都可以重写。

 

– textRectForBounds:    //重写来重置文字区域

– drawTextInRect:        //改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.

– placeholderRectForBounds:  //重写来重置占位符区域

– drawPlaceholderInRect:  //重写改变绘制占位符属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数,就不用调用super了.

– borderRectForBounds:  //重写来重置边缘区域

– editingRectForBounds:  //重写来重置编辑区域

– clearButtonRectForBounds:  //重写来重置clearButton位置,改变size可能导致button的图片失真

– leftViewRectForBounds:

– rightViewRectForBounds:

 

22.调整键盘

inputView //代替标准的系统键盘

inputAccessoryView //编辑时显示在系统键盘或用户自定义的inputView上面的视图

 

23. delegate

类要遵守UITextFieldDelegate协议

 

text.delegate = self; 声明text的代理是我,我会去实现把键盘往下收的方法 这个方法在UITextFieldDelegate里所以我们要遵守UITextFieldDelegate这个协议

 

- (BOOL)textFieldShouldReturn:(UITextField*)textField

{

    [textresignFirstResponder];    //主要是[receiverresignFirstResponder]在哪调用就能把receiver(text)对应的键盘往下收

return YES;

}

 

代理方法 

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ 

  

//返回一个BOOL值,YES代表允许编辑,NO不允许编辑. 

    return YES; 

} 

 

- (void)textFieldDidBeginEditing:(UITextField *)textField{ 

 //开始编辑时触发,文本字段将成为first responder 

} 

 

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ 

//返回BOOL值,指定是否允许文本字段结束编辑,当编辑结束,文本字段会让出first responder 

  //要想在用户结束编辑时阻止文本字段消失,可以返回NO ,返回NO,点击键盘的返回按钮会无效果。

  //这对一些文本字段必须始终保持活跃状态的程序很有用,比如即时消息 

  

    return NO; 

} 

- (void)textFieldDidEndEditing:(UITextField*)textField;{

 

}// 上面返回YES后执行;上面返回NO时有可能强制执行(e.g.view removed from window)

 

- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 

//当用户使用自动更正功能,把输入的文字修改为推荐的文字时,就会调用这个方法。 

//这对于想要加入撤销选项的应用程序特别有用 

//可以跟踪字段内所做的最后一次修改,也可以对所有编辑做日志记录,用作审计用途。   

//要防止文字被改变可以返回NO 

//这个方法的参数中有一个NSRange对象,指明了被改变文字的位置,建议修改的文本也在其中 

 

    return YES; 

} 

 

- (BOOL)textFieldShouldClear:(UITextField *)textField{ 

 

//返回一个BOOL值指明是否允许根据用户请求清除内容 

//可以设置在特定条件下才允许清除内容 

 

    return YES; 

} 

 

-(BOOL)textFieldShouldReturn:(UITextField *)textField{ 

 

//返回一个BOOL值,指明是否允许在按下回车键时结束编辑 

 //如果允许要调用resignFirstResponder 方法,这回导致结束编辑,而键盘会被收起[textField resignFirstResponder];

//查一下resign这个单词的意思就明白这个方法了 

    return YES; 

} 

 

 

 

24.通知

UITextField派生自UIControl,所以UIControl类中的通知系统在文本字段中也可以使用。除了UIControl类的标准事件,你还可以使用下列UITextField类特有的事件

 

UITextFieldTextDidBeginEditingNotification

UITextFieldTextDidChangeNotification

UITextFieldTextDidEndEditingNotification

当文本字段退出编辑模式时触发。通知的object属性存储了最终文本。

 

因为文本字段要使用键盘输入文字,所以下面这些事件发生时,也会发送动作通知

 

UIKeyboardWillShowNotification  //键盘显示之前发送

UIKeyboardDidShowNotification   //键盘显示之后发送

UIKeyboardWillHideNotification  //键盘隐藏之前发送

UIKeyboardDidHideNotification   //键盘隐藏之后发送

 

 

25.Stroyboard中:

1、Text :设置文本框的默认文本。

2、Placeholder : 可以在文本框中显示灰色的字,用于提示用户应该在这个文本框输入什么内容。当这个文本框中输入了数据时,用于提示的灰色的字将会自动消失。

3、Background :

4、Disabled : 若选中此项,用户将不能更改文本框内容。

5、接下来是三个按钮,用来设置对齐方式。

6、Border Style : 选择边界风格。

7、Clear Button : 这是一个下拉菜单,你可以选择清除按钮什么时候出现,所谓清除按钮就是出一个现在文本框右边的小 X ,你可以有以下选择:

    7.1 Never appears : 从不出现

    7.2 Appears while editing : 编辑时出现

    7.3 Appears unlessediting : 

    7.4 Is always visible : 总是可见

8、Clear when editingbegins : 若选中此项,则当开始编辑这个文本框时,文本框中之前的内容会被清除掉。比如,你现在这个文本框 A 中输入了 "What" ,之后去编辑文本框 B,若再回来编辑文本框 A ,则其中的 "What" 会被立即清除。

9、Text Color : 设置文本框中文本的颜色。

10、Font : 设置文本的字体与字号。

11、Min Font Size : 设置文本框可以显示的最小字体(不过我感觉没什么用)

12、Adjust To Fit : 指定当文本框尺寸减小时,文本框中的文本是否也要缩小。选择它,可以使得全部文本都可见,即使文本很长。但是这个选项要跟 Min Font Size 配合使用,文本再缩小,也不会小于设定的 Min Font Size 。

接下来的部分用于设置键盘如何显示。

13、Captitalization : 设置大写。下拉菜单中有四个选项:

    13.1 None : 不设置大写

    13.2 Words : 每个单词首字母大写,这里的单词指的是以空格分开的字符串

    13.3 Sentances : 每个句子的第一个字母大写,这里的句子是以句号加空格分开的字符串

    13.4 All Characters : 所以字母大写

14、Correction : 检查拼写,默认是 YES 。

15、Keyboard : 选择键盘类型,比如全数字、字母和数字等。

16、Appearance:

17、Return Key : 选择返回键,可以选择 Search 、 Return 、 Done 等。

18、Auto-enable ReturnKey : 如选择此项,则只有至少在文本框输入一个字符后键盘的返回键才有效。

19、Secure : 当你的文本框用作密码输入框时,可以选择这个选项,此时,字符显示为星号。

 

 

1.Alignment Horizontal 水平对齐方式

2.Alignment Vertical 垂直对齐方式

3.用于返回一个BOOL值 输入框是否 Selected(选中)Enabled(可用) Highlighted(高亮)

 

 

 

 

26.UITextField实例一 : UITextField限制字符 (只为数字)

 

ios代码  

1.  #define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz "  

2.  #define NUMBERS @"0123456789n"  

3.  #define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 "  

4.  #define NUMBERSPERIOD @"0123456789."  

5.    

6.    

7.  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  

8.  {  

9.  NSCharacterSet *cs;  

10. cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERSPERIOD ] invertedSet]; //invertedSet 方法是去反字符,把所有的除了字的字符都找出  

11.   

12. NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];  //componentsSeparatedByCharactersInSet 方法是把输入框输入的字符string 根据cs中字符一个一个去除cs字符并分割成字符并 NSArray, 然后componentsJoinedByString 是把NSArray 的字符通 ""无间隔接成一个NSString字符 赋给filtered.就是只剩字了.  

13.   

14.   

15. BOOL basicTest = [string isEqualToString:filtered];  

16.  if(!basicTest)   

17.   

18.         {  

19.             UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"  

20.                                                             message:@"输入"  

21.                                                            delegate:nil  

22.                                                   cancelButtonTitle:@"确定"  

23.                                                   otherButtonTitles:nil];  

24.               

25.             [alert show];  

26.             [alert release];  

27.             return NO;  

28.         }      

29.   

30. // Add any predicate testing here  

31. return basicTest;  

32. }  

 

#define NUMBERS @”0123456789n” (这个代表可以输入数字和换行,请注意这个n,如果不写这个,Done按键将不会触发,如果用在SearchBar中,将会不触发Search事件,因为你自己限制不让输入n,好惨,我在项目中才发现的。) 所以,如果你要限制输入英文和数字的话,就可以把这个定义为: #define kAlphaNum@”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″。 当然,你还可以在以上方法return之前,做一提示的,比如提示用户只能输入数字之类的。如果你觉得有需要的话。

 

实例:限制只能输入一定长度的字符

ios代码  

1.  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;   

2.  { //string就是此输入的那个字符 textField就是此正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反  

3.       

4.  if ([string isEqualToString:@"n"]) //按回车可以改变  

5.      {   

6.          return YES;   

7.      }   

8.     

9.      NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的  

10.    

11.     if (self.myTextField == textField) //是否想要限定的那个输入框  

12.     {   

13.         if ([toBeString length] > 20) { //如果输入框容大于20则弹出警告  

14.   textField.text = [toBeString substringToIndex:20];   

15.             UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:nil message:@"最大字不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil] autorelease];   

16.             [alert show];   

17.             return NO;   

18.         }   

19.     }   

20.     return YES;   

21. }  

 

 

27.UITextField实例二:

在UISearchBar中,当输入信息改变时,它就会调用textDidChange函数,但是UITextField没有这个功能,唯一与这个类似的shouldChangeCharactersInRange函数,也是在文件还没有改变前就调用了,而不是在改变后调用,要想实现这个功能,我们可以增加事件监听的方式.先来看看objective-c提供的接口:

ios代码  

1.  // add target/action for particular event. you can call this multiple times and you can specify multiple target/actions for a particular event.  

2.  给特殊事件添加目标或者方法,你能够调用这个方法多次,给特殊事件指定很多目标或者方法

3.  // passing in nil as the target goes up the responder chain. The action may optionally include the sender and the event in that order  

4.  给target传递空,会建立响应链,在这行命令,方法可以选择包含方法发送者和事件两个参数。

5.  // the action cannot be NULL.   方法不能为空。

6.  - (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;  

 怎么去使用这个接口呢?主要分为两步,第一步就是在UItextField组件中增加对文件编辑改变时事件的监听,然后再实现监听器监听到事件时,所调用的方法.

ios代码  

1.  //第一步,对组件增加听器 可以在viewDidLoad 方法中加入 textField 你自定义输入框的名  

2.  [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];  

3.  ...  

4.  //第二步,  

5.  - (void) textFieldDidChange:(id) sender {  

6.      UITextField *_field = (UITextField *)sender;  

7.      NSLog(@"%@",[_field text]);  

8.  }  

 

28.UITextField实例三:

UITextField控件处理键盘弹出时遮住输入框的问题

打开键盘卷动文本字段

默认情况下打开键盘会遮住下面的view,带来一点点困扰,不过这不是什么大问题,我们使用点小小的手段就可以解决。

 

首先我们要知道键盘的高度是固定不变的,不过在IOS 5.0 以后键盘的高度貌似不是216了,不过不要紧,我们调整调整就是了:

 

 

iPhone

ipad

竖屏(portrait)

216

264

横屏(landScape)

140

352

 

我们采取的方法就是在textField(有可能是其他控件)接收到弹出键盘事件时把self.view整体上移216px了(我们就以iPhone竖屏为例了)。

首先我们要设置textField的代理,我们就设为当前控制器了。

 

ios代码  

1.  textField,delegate=self;  

  

然后我们在当前控制器实现下面两个委托方法:

ios代码  

1.  - (void)textFieldDidBeginEditing:(UITextField *)textField  

2.  { //点触textField部,编辑都会个方法。textFieldfirst responder   

3.         NSTimeInterval animationDuration = 0.30f;      

4.        CGRect frame = self.view.frame;  

5.        frame.origin.y -=216;  

6.        frame.size.height +=216;  

7.        self.view.frame = frame;  

8.         [UIView beginAnimations:@"ResizeView" context:nil];  

9.         [UIView setAnimationDuration:animationDuration];  

10.        self.view.frame = frame;                  

11.        [UIView commitAnimations];                  

12. }  

ios代码 

1.  - (BOOL)textFieldShouldReturn:(UITextField *)textField   

2.  {//用户按下ruturn,把焦点从textField那么键盘就会消失了  

3.          NSTimeInterval animationDuration = 0.30f;  

4.          CGRect frame = self.view.frame;      

5.          frame.origin.y +=216;        

6.          frame.size. height -=216;     

7.          self.view.frame = frame;  

8.      //self.view移回原位置    

9.      [UIView beginAnimations:@"ResizeView" context:nil];  

10.     [UIView setAnimationDuration:animationDuration];  

11.         self.view.frame = frame;                  

12.         [UIView commitAnimations];  

13.         [textField resignFirstResponder];     

14. }     


二.UITableView

UITableView内置了两种样式:UITableViewStylePlain,UITableViewStyleGrouped

 

<UITableViewDataSource,UITableViewDelegate>里的方法:

tableView处理步骤

#pragma mark 1.有多少组

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

#pragma mark 2.section组头部控件有多高

-(CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section

#pragma mark 3.section组有多少行

-(NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section

#pragma mark 4.indexPath这行的cell有多高

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

#pragma mark 5.indexPath这行的cell长什么样子

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath

#pragma mark 6.section组头部显示什么控件

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

 

 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

 

//每当有一个cell进入视野屏幕就会调用,所以在这个方法内部就需要优化。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

if(cell==nil){

     //在这里面做创建的工作。循环优化。防止刷新cell进入屏幕的时候重复的创建

}

}

 

//当调用reloadData的时候,会重新刷新调用数据源内所有方法,其他事情都不会做呀

 [self reloadData]

 

 //这个方法只有在一开始有多少条数据才会算多少个高度,这个方法只会调用一次,但是每次reloadData的时候也会调用

 //而且会一次性算出所有cell的高度,比如有100条数据,一次性调用100

- (CGFloat)tableView:(UITableView *)tableViewheightForRowAtIndexPath:(NSIndexPath *)indexPath

 

 

 

 

-(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView //右侧索引

 

    -(void)tableView:(UITableView *)tableViewdidSelectRowAtIndexPath:(NSIndexPath *)indexPath //行点击事件

 

NSIndexPath *path = [self.tableView indexPathForSelectedRow]; //获得被选中的indexPath可以得到section,row

  

[self.tableView reloadRowsAtIndexPaths:[self.tableView indexPathsForSelectedRows] withRowAnimation:UITableViewRowAnimationNone]; //刷新table指定行的数据

        

   [self.tableView reloadData]; //刷新table所有行的数据

 

 

UITableView常用属性:

    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain]; // 初始化表格

    分隔线属性

tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;//UITableViewCellSeparatorStyleNone;

[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone]; //取消分隔线

    tableView.separatorColor = [UIColor lightGrayColor];

   

    条目多选

tableView.allowsMultipleSelection = YES;

    

    // 设置标题行高

[_tableView setSectionHeaderHeight:kHeaderHeight];

    [_tableView setSectionFooterHeight:0];

 

    // 设置表格行高

 [_tableView setRowHeight:50];

 

//设置背景色

self.tableView.backgroundView  优先级高,如果要设置backgroundColor的时候要先把view设置为nil

self.tableView.backgroundColor

 

//tableView的头部或者尾部添加view,footerView宽度是不用设置的

      xxxView.bounds = CGRectMake(0,0,0,height);

    self.tableView.tableFooterView =xxxView;

       self.tableView.tableHeaderView =xxxView;

 

UIButton *bt = (UIButton*)[self.contentView viewWithTag:i+100];

 

增加tableview滚动区域

self.tableView.contentInset = UIEdgeInsetsMake(0, 0, xx, 0); 

UITableViewCell

//创建UITableViewCell         

UITableViewCell *cell = [[UITableViewCell alloc]

initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];

       

       [cell.textLabel setBackgroundColor:[UIColor clearColor]];//清空标签背景颜色

       

        cell.backgroundView =xx; //设置背景图片

        cell.backgroundVColor =xx;

        cell.selectedBackgroundView = selectedBgView; //设置选中时的背景颜色

 

      

  cell.accessoryView = xxxView; //设置右边视图

   [cell setAccessoryType:UITableViewCellAccessoryNone]; //设置右侧箭头 

 

[self setSelectionStyle:UITableViewCellSelectionStyleNone]; //选中样式

cell.selectionStyle = UITableViewCellSelectionStyleBlue;

 

//设置cell的高度

- (CGFloat)tableView:(UITableView *)tableViewheightForRowAtIndexPath:(NSIndexPath *)indexPath

 

contentView下默认有3个子视图,其中的2个是UILabel,通过textLabel和detailTextLabel属性访问,第3个是UIImageView,通过imageView属性访问.

  UITableViewCellStyleDefault,UITableViewCellStyleValue1, UITableViewCellStyleValue2,UITableViewCellStyleSubtitle

 

#pragma mark - 重新调整UITalbleViewCell中的控件布局

- (void)layoutSubviews{

[super layoutSubviews];

}

cell 里面还有一个contentView

UITableViewCell表格优化

UITableViewCell对象的重用原理:

重用原理:当滚动列表时,部分UITableViewCell会移出窗口,UITableView会将窗口外的UITableViewCell放入一个对象池中,等待重用。当UITableView要求dataSource返回UITableViewCell时,dataSource会先查看这个对象池,如果池中有未使用的UITableViewCell,dataSource会用新的数据配置这个UITableViewCell,然后返回给UITableView,重新显示到窗口中,从而避免创建新对象

还有一个非常重要的问题:有时候需要自定义UITableViewCell(用一个子类继承UITableViewCell),而且每一行用的不一定是同一种UITableViewCell(如短信聊天布局),所以一个UITableView可能拥有不同类型的UITableViewCell,对象池中也会有很多不同类型的UITableViewCell,时可能会得到错误类型的UITableViewCell那么UITableView在重用UITableViewCell。解决方案:UITableViewCell有个NSString *reuseIdentifier属性,可以在初始化UITableViewCell的时候传入一个特定的字符串标识来设置reuseIdentifier(一般用UITableViewCell的类名)。当UITableView要求dataSource返回UITableViewCell时,先通过一个字符串标识到对象池中查找对应类型的UITableViewCell对象,如果有,就重用,如果没有,就传入这个字符串标识来初始化一个UITableViewCell对象

 

/**

单元格优化

 1. 标示符统一,使用static的目的可以保证表格标示符永远只有一个

 2. 首先在缓冲池中找名为"myCell"的单元格对象

 3. 如果没有找到,实例化一个新的cell

 **/

- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellIdentifier = @"myCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

//使用这种方法不用判断下面的cell

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    if (cell == nil) {       

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];

    }

return cell;

}

 

表格的编辑模式

删除、插入

- (void)setEditing:(BOOL)editing animated:(BOOL)animated; 开启表格编辑状态

 

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{

       返回表格编辑编辑样式。不实现默认都是删除

return editingStyle : UITableViewCellEditingStyleDelete,UITableViewCellEditingStyleInsert

}

 

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyleforRowAtIndexPath:(NSIndexPath *)indexPath{

      //根据editingStyle处理是删除还是添加操作

             完成删除、插入操作刷新表格

- (void)insertRowsAtIndexPaths:(NSArray *)indexPathswithRowAnimation:(UITableViewRowAnimation)animation;

 

-(void)deleteRowsAtIndexPaths:(NSArray *)indexPathswithRowAnimation:(UITableViewRowAnimation)animation;

}

 

移动

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPathtoIndexPath:(NSIndexPath *)destinationIndexPath

sourceIndexPath 移动的行   

destinationIndexPath 目标的行

 

自定义表格行UITableViewCell

storyboard方式创建:

直接拖到UITableView里面设置UITableViewCell

注意:

1.通过XIB或者Storyboard自定义单元格时,在xib和Storyboard里面需要指定单元格的可重用标示符Identifier

 

2.注意表格的优化中的差别

在Storyboard中两者等效

xxCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

xxCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

 

在xib文件中有差别:

第一种情况,只能在iOS6以上使用,如果在viewDidLoad注册了nib文件,并且指定了“单元格”的可重用标示符,那么    

    dequeueReusableCellWithIdentifier:

    dequeueReusableCellWithIdentifier:forIndexPath:

     方法是等效的。如果在viewDidLoad中注册了nib文件,表格缓冲池中的管理,有系统接管!

 

第二种情况,是在iOS 4以上均可以使用,如果没有在viewDidLoad注册nib文件,那么,只能使用

    dequeueReusableCellWithIdentifier:并且需要判断cell没有被实例化,并做相应的处理

 

 

在代码创建中差别:

用代码创建cell中的处理和nib一样,注册了cell就有系统接管并且可以用带forIndexPath的方法,没有注册就要自己去实例化cell,不能用带forIndexPath的方法

[tableView registerClass:XxxCell class] forCellReuseIdentifier:@"xxCell"];

 

xib方式创建:

//注册Identifier

- (void)viewDidLoad{

    [super viewDidLoad];

    /**

     注意:以下几句注册XIB的代码,一定要在viewDidLoad中!

     注册XIB文件,获得根视图,并且转换成TableView,tableView注册xib

     Identifier要在xib文件中定义,并且保持一致

     **/

    UINib *nib = [UINib nibWithNibName:@"BookCell" bundle:[NSBundle mainBundle]];

    UITableView *tableView = (UITableView *)self.view;

    [tableView registerNib:nib forCellReuseIdentifier:@"bookCell"];   

}

 

//没有注册Identifier只能使用下面方法

static NSString *CellIdentifier= @"bookCell";

BookCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

        cell = [[BookCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        NSBundle *bundle = [NSBundle mainBundle];

        NSArray *array = [bundle loadNibNamed:@"BookCell" owner:nil options:nil];

        cell = [array lastObject];

    }

 

 

代码方式创建:

1.                 建立UITableViewCell的类,继承UITableViewCell

2.                 往cell里面加入view的时候注意点:

//新建的组件放入contentView

[self.contentView addSubview:xxView];

 

//设置图片拉伸属性stretch

UIImage *normalImage = [UIImageimageNamed:@"xx.png"];

normalImage= [normalImage stretchableImageWithLeftCapWidth:

normalImage.size.width / 2 topCapHeight:normalImage.size.height / 2];

 

//在tableView里面viewDiDLoad里面要注册cell类

[tableView registerClass:XxxCell class] forCellReuseIdentifier:@"xxCell"];

 

自定义表格中Header

//自定义表格在这个方法中定义

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

 

三.UISwitch属性

1. onTintColor

  处于on时switch 的颜色
    switchImage.onTintColor = [UIColor grayColor];

2.tintColor 

处于off时switch 的颜色

    switchImage.tintColor = [UIColor greenColor];

3.onImage    

  设置on 的图标
    switchImage.onImage = [UIImage imageNamed:@"1.png"];

 

4. offImage

   设置off的图标
 switchImage.offImage = [UIImage imageNamed:@"4.png"];

 

5. on

设置switch的开关

swithImage.on = YES;

 

6.thumbTintColor

设置拇指颜色

swithImage.thumbTintColor = [UIColorredColor];

效果:

 

 

7.增加事件响应机制

监听的是这个事件:UIControlEventValueChanged,值改变事件

[switchImage addTarget:self action:@selector(switchOn) forControlEvents:UIControlEventValueChanged];

 

 

四.UISlide属性


1.     minimumValue  : 当值可以改变时,滑块可以滑动到最小位置的值,默认为0.0

_slider.minimumValue = 10.0;

2.     maximumValue : 当值可以改变时,滑块可以滑动到最大位置的值,默认为1.0

_slider.maximumValue = 100.0;

3.     continuous : 如果设置YES,在拖动滑块的任何时候,滑块的值都会改变。默认设置为YES

[_slider setContinuous:NO]; // 在滑块滑动结束时才获取滑块的值

 

4.     minimumValueImage : 滑块条最小值处设置的图片,默认为nil

 _slider.minimumValueImage = [UIImage imageNamed:@"003.png"];

 

5.     maximumValueImage,滑块条最大值处设置的图片,默认为nil

_slider.maximumValueImage = [UIImage imageNamed:@"002.png"];

6.minimumTrackTintColor : 小于滑块当前值滑块条的颜色,默认为蓝色

_slider.minimumTrackTintColor = [UIColor redColor];

7.maximumTrackTintColor: 大于滑块当前值滑块条的颜色,默认为白色

_slider.maximumTrackTintColor = [UIColor greenColor];

8.thumbTintColor : 当前滑块的颜色,默认为白色

_slider.thumbTintColor = [UIColor yellowColor];

 

 

9.currentMaximumTrackImage : 滑块条最大值处设置的图片

10.currentMinimumTrackImage : 滑块条最小值处设置的图片

11.currentThumbImage: 当前滑块的图片


 

五.UISegment属性

1.segmentedControlStyle

设置segment的显示样式。

typedef NS_ENUM(NSInteger,UISegmentedControlStyle) {

UISegmentedControlStylePlain,     // largeplain 系统默认平板样式

segmentedControl.segmentedControlStyle =UISegmentedControlStylePlain;

UISegmentedControlStyleBordered,  // largebordered 黑边样式

segmentedControl.segmentedControlStyle =UISegmentedControlStyleBordered;

UISegmentedControlStyleBar,       // small button/nav bar style. Tintable 条状样式

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

   UISegmentedControlStyleBezeled,   // DEPRECATED. Do not use this style. 这个类型不要使用,用了会报错喔。

};

 

2.tintColor 渐变颜色

Default tintColor is nil. Only used ifstyle is UISegmentedControlStyleBar

默认空,只有使用UISegmentedControlStyleBar,才能设置渐变颜色。

segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

segmentedControl.tintColor = [UIColor redColor];

效果:

 

3.momentary 设置在点击后是否恢复原样

默认为NO

segmentedControl.momentary = No;

 

点击之后效果:

segmentedControl.momentary = YES;

点击之后效果:

 

 

4. numberOfSegments(只读)

获取总选项数segmentedControl.numberOfSegments

 

5. selectedSegmentIndex

用来设置选中项或者返回选中项。

segmentedControl.selectedSegmentIndex =2;//设置默认选择项索引

segmentedControl.selectedSegmentIndex // 获取选中项

6.- (void)setTitle:(NSString *)title forSegmentAtIndex:(NSUInteger)segment;

[segmentedControl setTitle:@"two"forSegmentAtIndex:1];//设置指定索引的题目

效果:

7. - (void)setImage:(UIImage *)imageforSegmentAtIndex:(NSUInteger)segment;      

[segmentedControl setImage:[UIImage imageNamed:@"lan.png"]forSegmentAtIndex:3];//设置指定索引的图片

8.-(void)insertSegmentWithTitle:(NSString*)titleatIndex:(NSUInteger)segment animated:(BOOL)animated;

[segmentedControl insertSegmentWithTitle:@"add" atIndex:3 animated:NO];//在指定索引插入一个选项并设置题目

效果:

9.-(void)insertSegmentWithImage:(UIImage*)image  atIndex:(NSUInteger)segmentanimated:(BOOL)animated;

[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"mei.png"] atIndex:2 animated:NO];//在指定索引插入一个选项并设置图片

 

10.- (void)removeSegmentAtIndex:(NSUInteger)segmentanimated:(BOOL)animated;

[segmentedControl removeSegmentAtIndex:0 animated:NO];//移除指定索引的选项

效果:

11. - (void)removeAllSegments;

    //移除所有选项

//[segmentedControlremoveAllSegments];

 

12. - (void)setWidth:(CGFloat)widthforSegmentAtIndex:(NSUInteger)segment;        // set to 0.0 width to autosize. default is0.0

选项卡的宽度默认为0,此方法能够设置选项卡宽度。

[segmentedControl setWidth:70.0 forSegmentAtIndex:2];//设置指定索引选项的宽度

 

效果:

13. - (void)setContentOffset:(CGSize)offsetforSegmentAtIndex:(NSUInteger)segment; // adjustoffset of image or text inside the segment. default is (0,0)

[segmentedControl setContentOffset:CGSizeMake(10,0) forSegmentAtIndex:1];

设置选项卡内部文字或者图片与默认位置的偏移量,默认位置在选项卡的中心。

效果:

14. - (void)setEnabled:(BOOL)enabledforSegmentAtIndex:(NSUInteger)segment;       

 

[segmentedControl setEnabled:NO forSegmentAtIndex:4];//设置指定索引选项不可选

 

15.增加事件响应机制

监听的是这个事件:UIControlEventValueChanged,值改变事件

 

[segmentedControl addTarget:self action:@selector(itemClick)   forControlEvents:UIControlEventValueChanged];

 

六.UIScrollView

1.     contentOffset

默认CGPointZero,用来设置scrollView的滚动偏移量。

    // 设置scrollView的滚动偏移量

    scrollView.contentOffset = CGPointMake(0, 200);

2.     contentSize

默认CGSizeZero,用来设置scrollView的滚动范围。

    // 设置scrollView的滚动范围

    scrollView.contentSize = CGSizeMake( self.view.bounds.size.width, self.view.bounds.size.height * 2);

 

3.     contentInset

默认UIEdgeInsetsZero,用来设置scrollView的额外滚动区域。

// 设置scrollView的额外顶部滚动区域:(UIEdgeInsetsMake是逆时针设置,上左下右)

    scrollView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);

 

4. bounces

默认为YES,用来设置scrollView的弹簧效果

// 取消scrollView的弹簧效果

    scrollView.bounces = NO;

5.pagingEnabled

默认为NO,用来设置scrollView是否开启分页.

// 开启分页

    scrollView.pagingEnabled = YES;

6.scrollEnabled

默认为YES,用来设置scrollView是否允许滚动.

// scrollView禁止滚动

    scrollView.scrollEnabled = NO;

7.showsHorizontalScrollIndicator

默认为YES,用来设置scrollView是否显示水平滚动条.

// 隐藏水平滚动条

    scrollView.showsHorizontalScrollIndicator = NO;

8.showsVerticalScrollIndicator

默认为YES,用来设置scrollView是否显示垂直滚动条.

// 隐藏垂直滚动条

    scrollView.showsVerticalScrollIndicator = NO;

 

9.minimumZoomScale

 

默认1.0,用来设置scrollView最少缩小比例.

// 设置scrollView允许子视图的最大放大比例

    scrollView.maximumZoomScale = 2;

 

10.maximumZoomScale

默认1.0,用来设置scrollView最大放大比例.

// 设置scrollView允许子视图的最小缩放比例

    scrollView.minimumZoomScale = 0.8;

 

 

11. delegate

类要遵守UIScrollViewDelegate协议

 

scrollView.delegate = self; 声明scrollView的代理是我, 这个方法在UIScrollViewDelegate里所以我们要遵守UIScrollViewDelegate这个协议

 

11.1当scrollView的偏移量一改变就会调用这个方法,即滚动scrollView就会调用。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView;                                              

11.2当scrollView缩放时,就会调用这个方法

- (void)scrollViewDidZoom:(UIScrollView *)scrollView NS_AVAILABLE_IOS(3_2);

 

11.3 即将拖拽的时候调用.

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView;

11.4 即将停止拖拽的时候调用

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollViewwithVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0);

11.5 停止拖拽的时候调用。

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollViewwillDecelerate:(BOOL)decelerate;

 

11.6 即将减速完成的时候调用。

- (void)scrollViewWillBeginDecelerating:(UIScrollView*)scrollView;  

11.7 减速完成的时候调用

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;     

 

 

 

11.8 返回需要缩放哪个视图,这个视图必须是scrollView里的子视图。

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;

 

// 列如:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

{

    return scrollView.subviews[0];

}

 

11.9 scrollView即将开始缩放

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollViewwithView:(UIView *)view NS_AVAILABLE_IOS(3_2);

11.10 scrollView完成缩放

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;

11.11没有开启分页的时候,代理方法调用顺序:

scrollViewWillBeginDragging –> scrollViewDidScroll-> scrollViewWillEndDragging -> scrollViewDidEndDragging

 

11.12 开启分页的时候,代理方法调用顺序

scrollViewWillBeginDragging -> scrollViewDidScroll-> scrollViewDidEndDragging ->scrollViewWillBeginDecelerating ->scrollViewDidScroll-> scrollViewDidEndDecelerating

 

12. directionalLockEnabled

指定控件是否只能在一个方向上滚动

 

13. decelerationRate

改变scrollerView的减速点位置

14. tracking 

监控当前目标是否正在被跟踪

15. dragging 

改变scrollerView的减速点位置                        

16. delaysContentTouches

 

控制视图是否延时调用开始滚动的方法         

17. canCancelContentTouches 

控制控件是否接触取消touch的事件 

18. indicatorStyle

设定滚动条的样式

19. decelerating

监控当前目标是否正在减速

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值