美文网首页
5.1 常见视图

5.1 常见视图

作者: 草根小强 | 来源:发表于2019-04-15 11:24 被阅读0次

【进度条】

    //    【进度条】
    UIProgressView * progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(40, 100, 200, 30)];
    //进度 (0 - 1)
    progressView.progress = 0.0;
    //颜色定制
    progressView.tintColor = [UIColor redColor];
    progressView.progressTintColor = [UIColor yellowColor];
    //未完成的进度条颜色
    progressView.trackTintColor = [UIColor blueColor];
    progressView.tag = 11;
    
    [self.view addSubview:progressView];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerGo:) userInfo:@"abc" repeats:YES];
- (void)timerGo:(NSTimer *)timer {
    NSString * abc = timer.userInfo;
    
    UIProgressView * pg = (id)[self.view viewWithTag:11];
//    pg.progress += 0.1;
    CGFloat progress = pg.progress + 0.1;
    [pg setProgress:progress animated:YES];
    
    if (pg.progress == 1) {
        [_timer setFireDate:[NSDate distantFuture]];
    }
}
- (void)dealloc {
    //销毁定时器
    if (_timer != nil) {
        [_timer invalidate];
//        [_timer setFireDate:[NSDate distantFuture]];
    }
}

【步数器】

   //    【步数器】
    UIStepper * stepper = [[UIStepper alloc] initWithFrame:CGRectMake(40, 130, 200, 44)];
    //步数器的最大值
    stepper.maximumValue = 20;
    stepper.minimumValue = 10;
    //步数器的当前值
    stepper.value = 17;
    [stepper addTarget:self action:@selector(step:) forControlEvents:UIControlEventValueChanged];
    //步数器属性设置
    //达到最大值之后,点+的作用
    stepper.wraps = YES;
    //设置是否能够自增长
    stepper.autorepeat = NO;
    //阶跃值就是点击一个加 值加多少
    stepper.stepValue = 2;
    
    //颜色
    stepper.tintColor = [UIColor orangeColor];
    //可以设置背景图片
    [stepper setBackgroundImage:[UIImage imageNamed:@"header_bg"] forState:UIControlStateNormal];
    [stepper setBackgroundImage:[UIImage imageNamed:@"header_bg"] forState:UIControlStateHighlighted];
    //可以设置分隔线
//    [stepper setDividerImage:[UIImage imageNamed:@"header_bg"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal];
    
    [self.view addSubview:stepper];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(40, 170, 200, 44)];
    label.tag = 12;
    label.text = @"小明今年17岁了";
    
    [self.view addSubview:label];
- (void)step:(UIStepper *)stepper {
    UILabel * label = (id)[self.view viewWithTag:12];
    label.text = [NSString stringWithFormat:@"小明今年%d岁了", (int)stepper.value];
}

【多段选择视图】

//    【多段选择视图】
    //多段选择器的items,是由字符串或者图片对象组成的数组
    UISegmentedControl * seg = [[UISegmentedControl alloc] initWithItems:@[@"左边", [UIImage imageNamed:@"Mole06"], @"右边"]];
    seg.frame = CGRectMake(40, 200, 200, 44);
    //属性
    //设置选中项的下标
    seg.selectedSegmentIndex = 0;
    
//    seg.numberOfSegments
    //多段选择器的元素可以进行增删
    [seg addTarget:self action:@selector(seg:) forControlEvents:UIControlEventValueChanged];
    
    //设置背景图片,设置分隔线,设置颜色
    seg.tintColor = [UIColor orangeColor];
//    [seg setBackgroundImage:[UIImage imageNamed:@"header_bg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    //设置分隔线
    [seg setDividerImage:[UIImage imageNamed:@"Mole06"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    
    [self.view addSubview:seg];
- (void)seg:(UISegmentedControl *)seg {
    
    
//    0 - (seg.numberOfSegments - 1)
    
#if 1
    if (seg.selectedSegmentIndex == 0 && seg.numberOfSegments == 2) {
        [seg insertSegmentWithImage:[UIImage imageNamed:@"Mole06"] atIndex:1 animated:YES];
    } else if (seg.selectedSegmentIndex == 2 && seg.numberOfSegments == 3) {
        [seg removeSegmentAtIndex:1 animated:YES];
    }
#else
    if (seg.numberOfSegments == 3 && seg.selectedSegmentIndex == 0) {
        [seg removeSegmentAtIndex:1 animated:YES];
    }else if (seg.numberOfSegments == 2 && seg.selectedSegmentIndex ==  1) {
        [seg insertSegmentWithImage:[UIImage imageNamed:@"Mole06"] atIndex:1 animated:YES];
    }

    
#endif
    
}

UITextView 【文本视图】

//    【文本视图】
//    UITextField
    UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(40, 280, 60, 80)];
    textView.backgroundColor = [UIColor orangeColor];
//    textView.inputView
//    textView.inputAccessoryView
//    textView.keyboardAppearance
//    textView.keyboardType
//    textView.font
//    textView.text
//    textView.delegate
    
    //文本视图可以滚动
    //UITextView : UIScrollView
    //UITableView : UIScrollView
    //UICollectionView : UIScrollView
    [self.view addSubview:textView];
    
}
常见视图.png

滑动控件UISlider

UISlider跟UISwitch有点儿类似,都是继承自UIControl
既然UISlider是表示一个CGRange,那么就有一个最大值(maximumValue)和一个最小值(minimumValue),既然UISlider又是一个选择器,那么就有一个当前的选择值(value),这三个值都是UISlider的属性。
同样的,UISlider选择器被改变时,会触发UIControlEventValueChanged的事件,所以我们可以通过添加addTarget:::方法为事件添加处理方法。

#import "ViewController.h"

@interface ViewController ()

//滑动控件

@property(nonatomic,strong)UISlider *slider;

//标签控件

@property (nonatomic, strong)UILabel * myLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //将滑动控件添加到视图上
    
    [self.view addSubview:self.slider];
    
    //将标签添加到视图上
    
    [self.view addSubview:self.myLabel];
    
    _slider.frame=CGRectMake((self.view.frame.size.width-300)/2,(self.view.frame.size.width)/2, 300, 50);
    
    //minimunmValue 当值可以改变时,滑动为最小。默认为0.0
    
    _slider.minimumValue=0.0;
    
    //maximumValue 当值可以改变时,滑动为最大。默认为1.0
    
    _slider.maximumValue=100;
    
    //当前值为多少
    
    _slider.value=20;
    
    //设置为yes,在拖动滑块的时候,滑动的值会改变。默认值为yes
    
    [_slider setContinuous:YES];
    
    //设置最小处的图片。 默认为空
    
    _slider.minimumValueImage=[UIImage imageNamed:@""];
    
    //设置最大处的图片。 默认为空
    
    _slider.maximumValueImage=[UIImage imageNamed:@""];
    
    //小于当前滑动的颜色
    
    _slider.minimumTrackTintColor=[UIColor blueColor];
    
    //大于当前滑动的颜色
    
    _slider.maximumTrackTintColor=[UIColor redColor];
    
    //当前滑动值的颜色
    
    _slider.thumbTintColor=[UIColor blueColor];
    
    //添加事件
    
    [_slider addTarget:self action:@selector(sliderbutton:) forControlEvents:UIControlEventValueChanged];
    
    //对label位置
    
    _myLabel.frame=CGRectMake((self.view.frame.size.width-100)/2, (self.view.frame.size.height)/2, 100, 60);
    
    //字体
    
    _myLabel.font=[UIFont systemFontOfSize:_slider.value];
    
    //内容
    
    _myLabel.text=@"你好";
    
    
    /*
     
     currentMaximumTrackImage :滑块条最大值处设置的图片
     currentMinimumTrackImage : 滑块条最小值处设置的图片
     currentThumbImage: 当前滑块的图片
     
     */
    
    
}


//初始化滑动控件
- (UISlider *)slider{
    
    if (_slider==nil) {
        
        _slider=[[UISlider alloc]init];
        
    }
    
    return _slider;
    
}

//初始化标签
- (UILabel *)myLabel{
    
    if (_myLabel==nil) {
        
        _myLabel=[[UILabel alloc]init];
        
    }
    
    return _myLabel;
    
}

//slider的事件
-(void)sliderbutton:(id)sender{
    
    //确定一个对象是否是一个类的成员,或者是派生自该类的成员
    if ([sender isKindOfClass:[UISlider class]]) {
        
        //强制转化
        
        UISlider *slider=(UISlider*)sender;
        
        //字体大小
        _myLabel.font=[UIFont systemFontOfSize:slider.value];
        
    }
    
}

UIAlertView

#import "LNBUIAlertViewViewController.h"

@interface LNBUIAlertViewViewController ()

@end

@implementation LNBUIAlertViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(40, 120, 200, 40)];
    button.backgroundColor = [UIColor yellowColor];
    [button setTitle:@"Show Alert" forState:UIControlStateNormal];
    button.tag = 11;
    [button addTarget:self action:@selector(createAlertView) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:button];
    [button release];
}

- (void)createAlertView {
    UIAlertView * alert = [[UIAlertView alloc] initWithFrame:CGRectMake(80, 200, 200, 90)];
    alert.title = @"Hello";
    alert.message = @"I am Han Meimei.";
    alert.cancelButtonIndex = 2;
    alert.delegate = self;
    //index == 0 取消按钮,永远在最下面
    [alert addButtonWithTitle:@"OK"];
    [alert addButtonWithTitle:@"Cancel"];
    [alert addButtonWithTitle:@"Here"];
    
    //样式
    alert.alertViewStyle = UIAlertViewStyleDefault;
//    UIAlertViewStyleDefault = 0,
//    UIAlertViewStyleSecureTextInput,      //带一个密文text field
//    UIAlertViewStylePlainTextInput,       //带一个普通的text field
//    UIAlertViewStyleLoginAndPasswordInput //带一个登录界面
    
    //alert view不需添加到父视图上(其实是添加到window上)
    //alert view出现时,其他视图全部停止工作
    [alert show];
    //show之后会保留,可以release
    [alert release];
}

#pragma mark - Alert View Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"%ld", buttonIndex);
}

- (void)alertViewCancel:(UIAlertView *)alertView {
    NSLog(@"alertViewCancel");
}

- (void)willPresentAlertView:(UIAlertView *)alertView {
    NSLog(@"willPresentAlertView");
}

- (void)didPresentAlertView:(UIAlertView *)alertView {
    NSLog(@"didPresentAlertView");
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"willDismissWithButtonIndex %ld", buttonIndex);
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"didDismissWithButtonIndex %ld", buttonIndex);
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView {
    NSLog(@"alertViewShouldEnableFirstOtherButton");
    return NO;
}
@end

[提示窗UIAlertView与UIAlertController的用法(持续更新中)]

一般在if判断中加入
1.第一种基础型


image.png

全都在xxx.m功能文件中编写

UIAlertView(基础版):

1 UIAlertView *WXinstall=[[UIAlertView alloc]initWithTitle:@"提示框" message:@"提示信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];//一般在if判断中加入
2 [WXinstall show];
//监听点击事件 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([btnTitle isEqualToString:@"取消"]) {
         NSLog(@"你点击了取消");
    }else if ([btnTitle isEqualToString:@"确定"] ) {
         NSLog(@"你点击了确定");
        NSString *str = [NSString stringWithFormat:
                         @"https://itunes.apple.com/cn/app/wei-xin/id414478124?mt=8"];11         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }//https在iTunes中找,这里的事件是前往手机端App store下载微信
}

UIAlertController(基础版):

UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"提示信息" preferredStyle:UIAlertControllerStyleAlert];//UIAlertControllerStyleAlert视图在中央
 UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];  
 UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {  
 NSString *str = [NSString stringWithFormat: 
 @"https://itunes.apple.com/cn/app/wei-xin/id414478124?mt=8"];  
  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];  
  }];//https在iTunes中找,这里的事件是前往手机端App store下载微信 
  [alertController addAction:cancelAction];  
  [alertController addAction:okAction]; 
 [self presentViewController:alertController animated:YES completion:nil];

2.第二种没得选型。

image.png

UIAlertView(基础版):

1 UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你确定要退出应用吗?" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
2 [alert show];

3.第三种多选型。

image.png

//UIAlertControllerStyleAlert在中央屏幕。

//UIAlertControllerStyleActionSheet在屏幕底部。

UIAlertView(基础版):iOS8都弃用这里就略。

UIAlertController(基础版):

UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleActionSheet];
 //UIAlertControllerStyleAlert在中央屏幕。
 //UIAlertControllerStyleActionSheet在屏幕底部。
        UIAlertAction *useCamera = [UIAlertAction actionWithTitle:@"使用相机拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"这里是要调用相机拍照功能");
        }];
        UIAlertAction *desAction = [UIAlertAction actionWithTitle:@"destructive" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"这里是要调用销毁功能");
        }];
        UIAlertAction *usePhoto = [UIAlertAction actionWithTitle:@"使用相册照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"这里是要调用相册功能");
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:useCamera];
        [alertController addAction:desAction];
        [alertController addAction:usePhoto];
        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];

如果手机没有安装微信客户端的情况下,不要提示用户去安装,因为可能遇到审核的人不小心把你的应用拒了。

UIAlertView和UIActionSheet在iOS8已经过期了,你仍然可以继续使用。UIAlertController这个接口类是一个定义上的提升,它添加简单,展示Alert和ActionSheet使用统一的API。因为UIAlertController使UIViewController的子类,他的API使用起来也会比较熟悉!

image.png
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择睡前时间(分钟)" message:nil preferredStyle:UIAlertControllerStyleAlert];
        NSArray *timeArr = @[@"5",@"10",@"15",@"20",@"30",@"60"];
        NSInteger timeCount = [timeArr count];
        for (int i=0; i<timeCount; i++) {
            [alertVC addAction:[UIAlertAction actionWithTitle:timeArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [sender setTitle:action.title forState:UIControlStateNormal];
            }]];
        }
        [self presentViewController:alertVC animated:YES completion:nil];

UIActivityIndicatorView 非常简单 ,就是一个转圈圈的控件

一、UIActivityIndicatorView的常用方法及属性

//初始化方法
- initWithActivityIndicatorStyle

//控制方法
- startAnimating   //开始转圈
- stopAnimating   //停止转圈
- isAnimating        //转圈的状态

//常用属性
hidesWhenStopped              //停止转圈后隐藏
activityIndicatorViewStyle     //样式
color                                   //颜色  (iOS 5  引入)
 
//样式
typedef enum { 
UIActivityIndicatorViewStyleWhiteLarge,   //白色圆圈 但是要大些
UIActivityIndicatorViewStyleWhite,           //白色圆圈
UIActivityIndicatorViewStyleGray,            //灰色圆圈
} UIActivityIndicatorViewStyle;

二、UIActivityIndicatorView的使用

UIActivityIndicatorView *testActivityIndicator = [UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite]];
testActivityIndicator.center = CGPointMake(100.0f, 100.0f);//只能设置中心,不能设置大小
[testActivityIndicator setFrame = CGRectMack(100, 100, 100, 100)];//不建议这样设置,因为UIActivityIndicatorView是不能改变大小只能改变位置,这样设置得到的结果是控件的中心在(100,100)上,而不是和其他控件的frame一样左上角在(100, 100)长为100,宽为100.
[self addSubview:testActivityIndicator];
testActivityIndicator.color = [UIColor redColor]; // 改变圈圈的颜色为红色; iOS5引入
[testActivityIndicator startAnimating]; // 开始旋转
[testActivityIndicator stopAnimating]; // 结束旋转
[testActivityIndicator setHidesWhenStopped:YES]; //当旋转结束时隐藏

UISegmentedControl 分段控件

一、简介
<<分段控件提供一栏按钮(有时称为按钮栏),但只能激活其中一个按钮。分段控件会导致用户在屏幕上看到的内容发生变化。它们常用于在不同类别的信息之间选择,或在不同的应用屏幕之间切换
<<继承关系:UISegmentedControl-->UIControl-->UIView-->UIResponder-->NSObject
格式为
1-->初始化(作用)

typedef enum {
UISegmentedControlStylePlain,     // large plain 有灰边的大白按钮,适合偏好设置单元
UISegmentedControlStyleBordered,  // large bordered 黑边的大白按钮,适用于表格单元
UISegmentedControlStyleBar,       // small button/nav bar style. tintable 小按钮,适合导航栏
UISegmentedControlStyleBezeled,   // large bezeled style. tintable
} UISegmentedControlStyle;(如果属性有枚举类型的话,这里会有枚举类型说明)


mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;//风格 (这是具体的例子)

@property(nonatomic) UISegmentedControlStyle segmentedControlStyle NS_DEPRECATED_IOS(2_0, 7_0, "The segmentedControlStyle property no longer has any effect") __TVOS_PROHIBITED;//废弃属性   (这是说明)

二、UISegmentedControl的属性(属性的顺序与苹果API一致)
1--> 初始化方法

NSArray *array = [NSArray arrayWithObjects:@"家具",@"灯饰",@"建材",@"装饰", nil];
UISegmentedControl *segment =[[UISegmentedControl alloc]initWithItems:array];
-(instancetype)initWithItems:(nullable NSArray *)items; // items 可以是 NSStrings or UIImages. 控件的大小会自动调整为适合的内容。

2-->设置UISegmentedControl的风格

typedef enum {
UISegmentedControlStylePlain,     // large plain 有灰边的大白按钮,适合偏好设置单元
UISegmentedControlStyleBordered,  // large bordered 黑边的大白按钮,适用于表格单元
UISegmentedControlStyleBar,       // small button/nav bar style. tintable 小按钮,适合导航栏
UISegmentedControlStyleBezeled,   // large bezeled style. tintable
} UISegmentedControlStyle;


mySegmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;//风格

@property(nonatomic) UISegmentedControlStyle segmentedControlStyle NS_DEPRECATED_IOS(2_0, 7_0, "The segmentedControlStyle property no longer has any effect") __TVOS_PROHIBITED;//废弃属性

3-->设置在点击后是否恢复原样

mySegmentedControl.momentary = YES;

@property(nonatomic,getter=isMomentary) BOOL momentary;             //如果设置,则在跟踪结束后,我们不会继续显示选定的状态。默认是 NO

4-->获取总选项数

[segment numberOfSegments];//得到segment的数量

@property(nonatomic,readonly) NSUInteger numberOfSegments;

5-->是否根据segment的内容改变segment的宽度

segment.apportionsSegmentWidthsByContent = YES;

@property(nonatomic) BOOL apportionsSegmentWidthsByContent NS_AVAILABLE_IOS(5_0);

6-->在指定索引插入一个选项并设置题目

[segmentedControl insertSegmentWithTitle:@"insert" atIndex:3 animated:NO];

-(void)insertSegmentWithTitle:(nullable NSString *)title atIndex:(NSUInteger)segment animated:(BOOL)animated;

7-->在指定索引插入一个选项并设置图片

[segmentedControl insertSegmentWithImage:[UIImage imageNamed:@"mei.png"] atIndex:2 animated:NO];

-(void)insertSegmentWithImage:(nullable UIImage *)image  atIndex:(NSUInteger)segment animated:(BOOL)animated;

8-->移除指定索引的选项

[segmentedControl removeSegmentAtIndex:0 animated:NO];

-(void)removeSegmentAtIndex:(NSUInteger)segment animated:(BOOL)animated;

9-->移出所有segment

[segment removeAllSegments];

-(void)removeAllSegments;

10-->设置指定索引的题目

[segmentedControl setTitle:@"two" forSegmentAtIndex:1];

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

11-->获取指定索引选项的标题

NSString* myTitle = [mySegmentedControl titleForSegmentAtIndex:1];

-(nullable NSString *)titleForSegmentAtIndex:(NSUInteger)segment;

12-->设置指定索引的图片

segmentedControl setImage:[UIImage imageNamed:@"btn_jyy.png"] forSegmentAtIndex:3];

-(void)setImage:(nullable UIImage *)image forSegmentAtIndex:(NSUInteger)segment;

13-->获取指定索引选项的图片

UIImage* myImage = [mySegmentedControl imageForSegmentAtIndex:2];

-(nullable UIImage *)imageForSegmentAtIndex:(NSUInteger)segment;

14-->设置Item的宽度

[segmentedControl setWidth:70.0 forSegmentAtIndex:2];

-(void)setWidth:(CGFloat)width forSegmentAtIndex:(NSUInteger)segment;

15-->获取指定索引选项的宽度

CGFloat  float =[segmentedControl widthForSegmentAtIndex:2];

-(CGFloat)widthForSegmentAtIndex:(NSUInteger)segment;

16-->设置内容偏移

[segment setContentOffset:CGSizeMake(10, 10) forSegmentAtIndex:2];

-(void)setContentOffset:(CGSize)offset forSegmentAtIndex:(NSUInteger)segment;

17-->获取内容偏移

CGSize size = [mySegmentedControl contentOffsetForSegmentAtIndex:2];

-(CGSize)contentOffsetForSegmentAtIndex:(NSUInteger)segment;

18-->设置segment是否可用

[segmentedControl setEnabled:NO forSegmentAtIndex:4];

-(void)setEnabled:(BOOL)enabled forSegmentAtIndex:(NSUInteger)segment;        // default is YES

19-->判断指定索引选项是否可选

BOOL enableFlag = [segmentedControl isEnabledForSegmentAtIndex:4];

-(BOOL)isEnabledForSegmentAtIndex:(NSUInteger)segment;

20-->设置默认选择项索引

segmentedControl.selectedSegmentIndex = 2;

@property(nonatomic) NSInteger selectedSegmentIndex;

21-->设置segments的颜色

segmentedControl.tintColor = [UIColor redColor];

@property(null_resettable,nonatomic,strong) UIColor *tintColor;

22-->设置背景图

typedef enum {
UIBarMetricsDefault,  //竖屏
UIBarMetricsLandscapePhone,  横屏
} UIBarMetrics;


[segment setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

-(void)setBackgroundImage:(nullable UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

23-->获取背景图

UIImage* myImage = [mySegmentedControl backgroundImageForState: UIControlStateNormal barMetrics: UIBarMetricsDefault];

-(nullable UIImage *)backgroundImageForState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

24-->设置标签之间分割线的图案

typedef enum {
UIBarMetricsDefault,  //竖屏
UIBarMetricsLandscapePhone,  横屏
} UIBarMetrics;


[segment setDividerImage:[UIImage imageNamed:@"234"] forLeftSegmentState:UIControlStateNormal   rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

-(void)setDividerImage:(nullable UIImage *)dividerImage forLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

25-->获取标签之间分割线的图案

UIImage* myImage = [mySegmentedControl dividerImageForLeftSegmentState: UIControlStateNormal
rightSegmentState: UIControlStateNormal
barMetrics: UIBarMetricsDefault];

-(nullable UIImage *)dividerImageForLeftSegmentState:(UIControlState)leftState rightSegmentState:(UIControlState)rightState barMetrics:(UIBarMetrics)barMetrics  NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

26-->通过Attribute字符串属性字典设置标签标题

[segC setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor redColor]} forState:UIControlStateNormal];

-(void)setTitleTextAttributes:(nullable NSDictionary *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

27-->获取Attribute字符串属性字典

NSDictionary *dic=[segmentedControl titleTextAttributesForState: UIControlStateNormal];

-(nullable NSDictionary *)titleTextAttributesForState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

28-->设置标签内容的偏移量

typedef NS_ENUM(NSInteger, UISegmentedControlSegment) {
UISegmentedControlSegmentAny = 0,//所有标签都受影响
UISegmentedControlSegmentLeft = 1,  //只有左边部分受到影响
UISegmentedControlSegmentCenter = 2, // 只有中间部分受到影响
UISegmentedControlSegmentRight = 3,  // 只有右边部分受到影响
UISegmentedControlSegmentAlone = 4,  // 在只有一个标签的时候生效
};


[segC setContentPositionAdjustment:UIOffsetMake(0, -60) forSegmentType: UISegmentedControlSegmentAlone
barMetrics: UIBarMetricsDefault];

-(void)setContentPositionAdjustment:(UIOffset)adjustment forSegmentType:(UISegmentedControlSegment)leftCenterRightOrAlone barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

29-->获取自定义偏移量

UIOffset offset= [segC s contentPositionAdjustmentForSegmentType: : UISegmentedControlSegmentAlone
barMetrics: UIBarMetricsDefault];

-(UIOffset)contentPositionAdjustmentForSegmentType:(UISegmentedControlSegment)leftCenterRightOrAlone barMetrics:(UIBarMetrics)barMetrics NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

UISegmentedControl自定义

需求样式如下:

image image

·每个segment都能被点击,相当于集成了多个button
·需求是 点击不同button切换不能的View 切换不同的页面。

由于我们产品设计中,对于这样的切换设计很多,每个模块都会设计到。所以就想到了,封装一个segmentView,使用方便。
使用者,只需要创建segmentView(传入几个item,就是几个button)然后会暴露segmentSwitchBlock的事件,用于处理不同页面之间的切换问题。下面就是代码。

代码块:
.h

#import <UIKit/UIKit.h>
#import "SCViewProtocol.h"

@interface SCSegmentView : UIView<SCViewProtocol>

@property (nonatomic,copy) void  (^segmentSwitchBlock) (long selectedSegmentIndex);

@property (nonatomic,assign) long selectedSegmentIndex;

- (instancetype)initWithItemList:(NSArray *)itemList;

@end

首先先针对这个SCViewProtocol协议说明一下:
SCViewProtocol这个协议定义了几个方法:
作用:省去了每次都要拼写的时间,让每一个参与该项目的开发者都遵循这个原则,对于排错有很好的帮助。清晰明了。
~传入的数组的目的:标题显示几个button会由数组的个数来决定,所以需要开发者传入一个数组,来显示标题内容。

#import <Foundation/Foundation.h>

@protocol SCViewProtocol <NSObject>
@optional;
//设置数据源
- (void)setViewWithModel:(id)obj;
//添加子视图
- (void)addSubViews;
//设置约束
- (void)setConstraints;

//初始化ui默认
- (void)configUIDefault;

- (void)reloadUI;

@end

.m

@interface SCSegmentView ()
@property (nonatomic, strong) UISegmentedControl *segment;
@property (nonatomic, strong) NSArray *itemList;

@end

@implementation SCSegmentView

-(instancetype)initWithItemList:(NSArray *)itemList{
    if (self = [super init]) {
        self.itemList = itemList;
        self.backgroundColor = [UIColor SCLightBlueColor];
        [self addSubViews];
        [self setConstraints];
    }
    return self;
}

-(void)addSubViews{
    [self addSubview:self.segment];
}

-(void)setConstraints{
    [self.segment mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(30);
        make.top.mas_equalTo(self.mas_top).mas_offset(10);
        make.width.mas_equalTo(self.mas_width).mas_offset(-50);
        make.centerX.mas_equalTo(self.mas_centerX);
    }];
}

创建UISegmentedControl

- (UISegmentedControl *)segment{
    if (!_segment) {
        _segment = [[UISegmentedControl alloc]initWithItems:self.itemList];
        _segment.tintColor = [UIColor SCWhiteColor];
        _segment.selectedSegmentIndex = 0;//选中第几个segment 一般用于初始化时选中
        [_segment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
        UIFont *font = [UIFont boldSystemFontOfSize:14.0f];
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
        [_segment setTitleTextAttributes:attributes forState:UIControlStateNormal];

        _segment.selectedSegmentIndex = 0;
        _segment.layer.masksToBounds = YES;
        _segment.layer.cornerRadius = 3;
        [_segment addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];
    }
    return _segment;
}

设置segment的字体:

//设置Segment的字体
    NSDictionary *dic = @{
                          //1.设置字体样式:例如黑体,和字体大小
                          NSFontAttributeName:[UIFont fontWithName:@"Arial-BoldMT" size:20],
                          //2.字体颜色
                          NSForegroundColorAttributeName:[UIColor grayColor]
                          };

    [segment setTitleTextAttributes:dic forState:UIControlStateNormal];

其他行为、外观、添加、删除等相关内容:

//设置segment的外观和字体颜色
    segment.tintColor = [UIColor redColor];
    //segment.segmentedControlStyle = UISegmentedControlStyleBar;此属性在ios7之后不再有任何效果

    [segment setEnabled:NO]; //设置segment是否可用 此方法是其父类UIControl的方法
    [segment setEnabled:NO forSegmentAtIndex:2];//设置下标为2的segment不可用
    [segment setWidth:100 forSegmentAtIndex:2]; //这时下表为2的segment的宽度
    [segment setContentOffset:CGSizeMake(10, 10) forSegmentAtIndex:2];//设置内容偏移
    segment.apportionsSegmentWidthsByContent = YES; //是否根据segment的内容改变segment的宽度

    [segment insertSegmentWithImage:[UIImage imageNamed:@"3"] atIndex:2 animated:YES]; //添加分页,并设置图片
    [segment insertSegmentWithTitle:@"ddd" atIndex:0 animated:YES];//添加分页,并设置标题
    [segment numberOfSegments];//得到segment的数量
    [segment removeAllSegments];//移出所有segment
    [segment removeSegmentAtIndex:2 animated:YES];//移出下标为2的segment
    segment.selectedSegmentIndex = 0;//选中第几个segment 一般用于初始化时选中

如果需要给这个segment增加图片,可以用下面的方法:

//设置下标为4的segment的图片
    [segment setImage:[UIImage imageNamed:@"kaixin"] forSegmentAtIndex:4];

切换事件

- (void)segmentValueChanged:(UISegmentedControl *)segment{
    self.segmentSwitchBlock?self.segmentSwitchBlock(segment.selectedSegmentIndex):nil;
}

存储当前点击segment的状态值

-(long)selectedSegmentIndex{
    return self.segment.selectedSegmentIndex;
}

具体使用:

-(SCSegmentView *)segmentView{
    if (!_segmentView) {
        _segmentView = [[SCSegmentView alloc]initWithItemList:@[@"我的待办",@"我的办结"]];
        @Weakify(self);
        _segmentView.segmentSwitchBlock = ^(long segmentIndex) {
        @Strongify(self);
        [self segmentValueChanged:segmentIndex];
        };
    }
    return _segmentView;
}

-(void)segmentValueChanged:(long)selectedSegmentIndex{
}

通过获取segmentView中index的值 来刷新数据

 if (self.segmentView.selectedSegmentIndex==0){
}

以上就是针对UISegmentedControl的View简单的封装。

UIActionSheet

#import "LNBUIActionSheetViewController.h"

@interface LNBUIActionSheetViewController ()

@end

@implementation LNBUIActionSheetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createActionSheet];
}

- (void)createActionSheet {
    UIActionSheet * action = [[UIActionSheet alloc] initWithTitle:@"分享" delegate:self cancelButtonTitle:@"撤销" destructiveButtonTitle:@"销毁" otherButtonTitles:@"QQ", @"微博", @"微信", nil];
    
    [action showInView:self.view];
    [action release];
    
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"第%lu个按钮被点击", buttonIndex);
}

- (void)actionSheetCancel:(UIActionSheet *)actionSheet {
    NSLog(@"actionSheet 被取消");
}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet {
    NSLog(@"actionSheet 即将出现");
}

- (void)didPresentActionSheet:(UIActionSheet *)actionSheet {
    NSLog(@"actionSheet 已经出现");
}

- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"actionSheet 被点击了第%ld个按钮 即将消失", buttonIndex);
}

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    NSLog(@"actionSheet 被点击了第%ld个按钮 已经消失", buttonIndex);
}
@end
UIActionSheet.png

相关文章

  • 5.1 常见视图

    【进度条】 【步数器】 【多段选择视图】 UITextView 【文本视图】 常见视图.png 滑动控件UISli...

  • OC之view手动布局视图

    1、设置子视图的frame 布局子视图:使用该方法直接设置子视图的frame 在iOS 5.1和更早版本上这个方法...

  • 视图

    视图1,虚拟表,mysql5.1版本出现的特性,是通过表动态的生成的数据。创建视图CREATE VIEW <视图名...

  • 视图

    视图虚拟表,和普通表一样使用Mysql5.1的新特性,通过普通表动态生成的数据 一、创建视图create view...

  • 【数据库系列】| 视图和子查询

    5.1视图 ● 从SQL的角度来看,视图和表是相同的,两者的区别在于表中保存的是实际的数据,而视图中保存的是 SE...

  • Spring Boot导出Pdf文件

    除了常见的jsp视图外,还有pdf,excel等。不管哪种视图,都会实现SpringMvc定义的视图接口View。...

  • 《SQL必知必会》笔记9-使用视图view、存储过程proced

    1 使用视图(VIEW) 1.1 视图 视图是虚拟的表,只包含使用时动态检索数据的查询。 视图的常见应用: 重用S...

  • Activity

    常见容器视图示例: Activity 会创建视图来向用户显示信息,并使用户与 Activity 互动。视图是 An...

  • layoutSubviews、setNeedsLayout 和

    layoutSubviews 方法 布局子视图。 此方法的默认实现在 iOS 5.1 及更早的版本中什么都不会做。...

  • 【laravel5.1-0.0.8】视图操作

    视图 在resources/views/下面; 格式viewname.blade.php 传值到页面 compac...

网友评论

      本文标题:5.1 常见视图

      本文链接:https://www.haomeiwen.com/subject/cihhwqtx.html