iOS -- UI常用组件总结

来源:互联网 发布:comtrade数据库 编辑:程序博客网 时间:2024/06/05 02:42

1. UITextField


文本输入框

1.0 声明实现代理

      <UITextFieldDelegate>

1.1 常用设置

textField.borderStyle = UITextBorderStyleRoundedRect; //圆边框textField.keyboardType = UIKeyboardTypePhonePad; // 键盘类型textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;[textField setFont:[UIFont boldSystemFontOfSize:12]]; // 字体textField.placeholder  = @"Simple text field"; //提示语textField.leftView = prefixLabel; // 左边显示一个labeltextField.leftViewMode = UITextFieldViewModeAlways; // 左边始终显示textField.clearButtonMode = UITextFieldViewModeAlways;//始终显示清除按钮textField.returnKeyType = UIReturnKeyDone;//return键显示为"Done"_passwordTextField.secureTextEntry = YES;//输入密码时使用[self.view addSubview:textField];textField.delegate = self; // 设置代理

1.2 代理方法

Return键

- (BOOL)textFieldShouldReturn:(UITextField *)textField {    [textField resignFirstResponder];   // 隐藏键盘,回到主响应区    return YES;}

开始编辑

- (void)textFieldDidBeginEditing:(UITextField *)textField {    NSLog(@"Text field did begin editing");}

结束编辑

- (void)textFieldDidEndEditing:(UITextField *)textField {    NSLog(@"Text Field did end editing");}

1.3 判断是否有输入

使用下面的判断,即时没有输入也能执行到if里面

if (_nameTextField.text != nil) {    ...}

解决方法是:

if (_nameTextField.text != nil && _nameTextField.text.length > 0) {    ...}

2. Label


静态文本框

2.1 常用设置

myLabel.text = @"label ";[myLabel setFont:[UIFont systemFontOfSize:14]];[myLabel sizeToFit];    // 适应文本大小myLabel.backgroundColor = [UIColor grayColor]; //背景色myLabel.textColor = [UIColor redColor]; //字体颜色myLabel.numberOfLines = 0; // 不限制行数aLabel.textAlignment = NSTextAlignmentCenter;//对齐方式

2.2 设置行间距

NSMutableParagraphStyle *paragraghStyle = [[NSMutableParagraphStyle alloc] init];[paragraghStyle setLineSpacing:10];//设置行间距poemContentLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:myText  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:paragraghStyle}]; // 设置label的attributedTextmyLabel.textAlignment = NSTextAlignmentCenter;myLabel.numberOfLines = 0;myLabel.lineBreakMode = NSLineBreakByWordWrapping;[self.view addSubview:myLabel];CGSize myLabelSize = [myLabel sizeThatFits: CGSizeMake(self.view.bounds.size.width, CGFLOAT_MAX)];poemContentLabel.frame = CGRectMake(0, 150, self.view.bounds.size.width, myLabelSize.height);//设置frame

3. Button


3.1 常用设置

UIButton *roundButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];//类型[roundButton setFrame:CGRectMake(60, 50, 200, 40)]; //大小[roundButton setTitle:@"Round Button" forState:UIControlStateNormal];//名称

当buttonType为UIButtonTypeCustom时,

[customButton setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];[customButton setBackgroundImage:[[UIImage imageNamed:@"whiteButton.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:20] forState:UIControlStateNormal]; //图片先拉伸再设置背景[customButton setBackgroundImage:[[UIImage imageNamed:@"back.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:20] forState:UIControlStateHighlighted];

4. Toolbar


4.1 常用设置

UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace                                                                           target:nil                                                                           action:nil];UIBarButtonItem *customItem1 = [[UIBarButtonItem alloc] initWithTitle:@"Tool1"                                                                style:UIBarButtonItemStylePlain                                                               target:self                                                               action:@selector(toolbarItem1:)];UIBarButtonItem *customItem2 = [[UIBarButtonItem alloc] initWithTitle:@"Tool2"                                                                style:UIBarButtonItemStyleDone                                                               target:self                                                               action:@selector(toolbarItem2:)];NSArray *toolbarItems = [NSArray arrayWithObjects:customItem1, spaceItem, customItem2, nil];UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 50,          self.view.bounds.size.width, 50)];[toolbar setBarStyle:UIBarStyleBlackOpaque];[toolbar setItems:toolbarItems];[self.view addSubview:toolbar];

5. Statusbar


5.1 常用设置

[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

6. Navigation Bar


6.1 常用设置

  • 设置UIWindow的rootViewController (为navigationController)
  • 设置NavigationController的rootViewControler
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];self.viewController = [[TextViewController alloc] init];self.navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];self.window.rootViewController = self.navController;
  • 添加navigation bar的rightButton
UIBarButtonItem *myNavBtn = [[UIBarButtonItem alloc] initWithTitle:@"myButton"                                                             style:UIBarButtonItemStylePlain                                                            target:self                                                            action:@selector(myButtonClicked:)];[self.navigationController.navigationBar setBarStyle:UIBarStyleDefault]; //navigationBar的样式[self.navigationItem setRightBarButtonItem:myNavBtn];
  • 压入一个新的View
TempViewController *tempVC = [[TempViewController alloc] init];[self.navigationController pushViewController:tempVC animated:YES];

7. Tab Bar


7.1 常用设置

FirstViewController *viewController1 = [[FirstViewController alloc] init];viewController1.tabBarItem.title = @"tabBar1";viewController1.tabBarItem.image = [UIImage imageNamed:@"clock"];SecondViewController *viewController2 = [[SecondViewController alloc] init];viewController2.tabBarItem.title = @"tabBar2";viewController2.tabBarItem.image = [UIImage imageNamed:@"alert"];self.tabBarController = [[UITabBarController alloc] init];self.tabBarController.viewControllers = @[viewController1, viewController2];[self.window setRootViewController:self.tabBarController];[self.window makeKeyAndVisible];



8. Image View


8.1 常用设置

UIImageView *imageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];//大小imageView.image = [UIImage imageNamed:@"dog"];//设置图片[imageView setContentMode:UIViewContentModeScaleAspectFill];//适应方式[UIImage imageWithCGImage:image.CGImageRef scale:1 orientation:UIImageOrientationDown];//图片镜像
  • 幻灯片播放
imageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"dog"],[UIImage imageNamed:@"boy"],nil];//设置需要播放的图片imageView.animationDuration = 10.0;imageView.contentMode = UIViewContentModeCenter;[imageView startAnimating];//开始播放[self.view addSubview:imageView];

9. Scroll View


9.1 常用设置

_myScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 20, self.view.bounds.size.width - 40, self.view.bounds.size.height - 100)];_myScrollView.accessibilityActivationPoint = CGPointMake(100, 100); //?_imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dog"]];_myScrollView.contentSize = CGSizeMake(_imageView.frame.size.width, _imageView.frame.size.height);//取景范围[_myScrollView addSubview:_imageView];_myScrollView.minimumZoomScale = 0.1;//最小缩到图片的10%_myScrollView.maximumZoomScale = 3;_myScrollView.pagingEnabled = NO;//分页_myScrollView.delegate = self;[self.view addSubview:_myScrollView];

9.2 代理方法

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView //缩放时必须实现- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView- (void)scrollViewDidScroll:(UIScrollView *)scrollView- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

10. Table View


10.1 声明实现代理

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

10.2 指定代理变量

myTableView.delegate = self;myTableView.dataSource = self;

10.3 代理方法

有多少个section

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

设置各个section的cell数目

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

设置Section Header/Footer内容

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

设置Section Header / Footer高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section

行高

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

设置单元格内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    static NSString *cellIdentifier = @"cellIdentifier";    BLCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];//重用    if (cell == nil) {        cell = [[BLCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];        cell.selectionStyle = UITableViewCellSelectionStyleGray; //选中时显示方式        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //单元格右边右边显示“>”        cell.delegate = self;    }    cell.text = @"hello world";    return cell;}

删除提示

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {    return @"delete";}

编辑时设置insert还是delete

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {    return UITableViewCellEditingStyleDelete;}

单元格insert/delete时具体行为

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {    if (editingStyle == UITableViewCellEditingStyleInsert) {        BLUser *user = [BLUser userWithName:@"zhangsan" headImagePath:nil lifePhotoPath:nil];        BLMessage *message = [BLMessage messageWithSender:user text:@"hello world" sendDate:[NSDate date]];        [_messageArray insertObject:message atIndex:indexPath.row];        [_tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];    } else if (editingStyle == UITableViewCellEditingStyleDelete) {        [_messageArray removeObjectAtIndex:indexPath.row];        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];    }}

设置哪些行可以编辑

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {    return YES;}

设置各Section的headerView和footerView

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

设置整个table的headerView和footerView

myTableView.tableHeaderView = headerView;myTableView.tableFooterView = footerView;

其他方法

删除一行

[myTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]                   withRowAnimation:UITableViewRowAnimationTop];

11. UITextView


  • 滚动文本框,继承自UIScrollView
  • 可以编辑文本

11.1 声明实现代理

@interface FirstViewController ()<UITextViewDelegate>

11.2 代理方法

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range {       if ([text isEqualToString:@"\n"]){        [textView resignFirstResponder];    }    return YES;}-(void)textViewDidBeginEditing:(UITextView *)textView-(void)textViewDidChange:(UITextView *)textView-(void)textViewDidEndEditing:(UITextView *)textView-(BOOL)textViewShouldEndEditing:(UITextView *)textView{    [textView resignFirstResponder];    return YES;}- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {    return  NO; //不可编辑,设置后相当于scroll label}



11.3 举例(swift)

声明一个textview

@IBOutlet weak var myTextview: UITextView!

遵从代理

class ViewController: UIViewController, UITextViewDelegate

设置代理,手势

myTextview.delegate = self //代理myTextview.layer.cornerRadius = 20.0 //圆角let gestrue: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "swipDown")gestrue.direction = UISwipeGestureRecognizerDirection.Down//下滑self.view.addGestureRecognizer(gestrue)let tap = UITapGestureRecognizer(target: self, action: "tap") //点击self.view.addGestureRecognizer(tap)

添加swipDown和tap方法:回到主响应区

// MARK: Custom methodsfunc swipDown() {    self.myTextview.resignFirstResponder()}func tap() {    self.myTextview.resignFirstResponder()}

这样,只要在myTextview外边下滑点击,都会回到主响应区。

12.View Transition


  • 切换View时的效果
  • eg,电子书翻页

添加2个View

self.view1 = [[UIView alloc] initWithFrame:self.view.frame];self.view1.backgroundColor = [UIColor cyanColor];self.view2 = [[UIView alloc] initWithFrame:self.view.frame];self.view2.backgroundColor = [UIColor orangeColor];[self.view addSubview:_view1];[self.view sendSubviewToBack:_view1];//作为背景视图

切换时的效果实现

- (void)doTransitionWithType:(UIViewAnimationOptions)animationTransitionType {    if ([[self.view subviews] containsObject:_view2]) {        [UIView transitionFromView:_view2                            toView:_view1                          duration:2                           options:animationTransitionType                        completion:^(BOOL finished) {                            [_view2 removeFromSuperview]; //移除_view2                        }];        [self.view addSubview:_view1];        [self.view sendSubviewToBack:_view1];    } else {        [UIView transitionFromView:_view1                            toView:_view2                          duration:2                           options:animationTransitionType                        completion:^(BOOL finished) {                            [_view1 removeFromSuperview];//移除_view1                        }];        [self.view addSubview:_view2];        [self.view sendSubviewToBack:_view2];    }}

curlUp效果(翻页仿真)

- (void)curlUp:(id)sender {    [self doTransitionWithType:UIViewAnimationOptionTransitionCurlUp];}



UIViewAnimationOptions

UIViewAnimationOptions Do UIViewAnimationOptionTransitionFlipFromLeft UIViewAnimationOptionTransitionFlipFromRight UIViewAnimationOptionTransitionFlipFromTop UIViewAnimationOptionTransitionFlipFromBottom UIViewAnimationOptionTransitionCurlUp UIViewAnimationOptionTransitionCurlDown UIViewAnimationOptionTransitionCrossDissolve 溶解 UIViewAnimationOptionTransitionNone

13.Pickers


13.1 声明实现代理

//因用到了textField所以加上UITextFieldDelegate<UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

13.2 添加一个PickerView

- (void)addPickerView {    _pickerArray = [[NSArray alloc] initWithObjects:@"Monday",@"Tuesday", @"Wednesday", @"Thursday", @"Friday",@"Saturday",@"Sunday", nil];    _myTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, self.view.bounds.size.width - 20, 30)];    _myTextField.borderStyle = UITextBorderStyleRoundedRect;    _myTextField.textAlignment = NSTextAlignmentCenter;    _myTextField.delegate = self;    [self.view addSubview:_myTextField];    [_myTextField setPlaceholder:@"Pick a day"];    _myPickerView = [[UIPickerView alloc] init];    _myPickerView.delegate = self;    _myPickerView.dataSource = self;    _myPickerView.showsSelectionIndicator = YES;    UIBarButtonItem *doneButton    = [[UIBarButtonItem alloc] initWithTitle:@"DONE"                                       style:UIBarButtonItemStyleDone                                      target:self                                      action:@selector(done:)];    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - _myPickerView.frame.size.height - 50, self.view.frame.size.width, 50)];    [toolBar setBarStyle:UIBarStyleBlackOpaque];    NSArray *toolbarItems = [NSArray arrayWithObjects:doneButton, nil];    [toolBar setItems:toolbarItems];    _myTextField.inputView = _myPickerView; //_myTextField激活时显示    _myTextField.inputAccessoryView = toolBar; //伴随inputView显示}

上面函数中,done: 方法为

- (void)done:(id)sender {    [_myTextField resignFirstResponder];}

13.3 代理方法

// 有几列pickerview- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {    return 1;}// 每个component分别有几行- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {    return _pickerArray.count;}// Picker选中行的处理- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {    [_myTextField setText:[_pickerArray objectAtIndex:row]];}// 设置PickerView每行的内容- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {    return [_pickerArray objectAtIndex:row];}

13.4 效果



14.Switches


14.1 添加一个Switch

UISwitch *newSwitch = [[UISwitch alloc] init];[self.view addSubview: newSwitch];newSwitch.center = CGPointMake(50, 300); //位置[newSwitch addTarget:self              action:@selector(newSwitched:)    forControlEvents:UIControlEventValueChanged];
- (void)newSwitched:(id)sender {    NSLog(@"Switch current state %@", _mySwitch.on ? @"On":@"Off");}

15.Slider


15.1 常用设置

    mySlider = [[UISlider alloc] initWithFrame:CGRectMake(20, 400, self.view.frame.size.width - 40, 23)];    mySlider.minimumValue = 10.0;    mySlider.maximumValue = 99.0;    mySlider.continuous = NO; //滑动停止才触发sliderChanged:    [mySlider  addTarget:self                  action:@selector(sliderChanged:)        forControlEvents:UIControlEventValueChanged];    [self.view addSubview:mySlider];



16.Alert


(废弃)16.1 常用设置

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title"                                                        message:@"This is a test alert"                                                       delegate:self                                              cancelButtonTitle:@"cancel"                                              otherButtonTitles:@"OK", nil];NSLog(@"%@", [alertView buttonTitleAtIndex:0]);[alertView show];

(废弃)16.2 代理

<UIAlertViewDelegate>
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {    switch (buttonIndex) {        case 0:            NSLog(@"cancel button clicked");            break;        case 1:            NSLog(@"OK button clicked");            break;        default:            break;    }}

16.3 使用UIAlertController (iOS 8)

UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil                                                               message:msg                                                        preferredStyle:UIAlertControllerStyleAlert];UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定"                                                  style:UIAlertActionStyleDefault                                                handler:nil];[alert addAction:action];[self presentViewController:alert animated:YES completion:nil];
0 0
原创粉丝点击