03-UISegmentedControl的基本使用

UISegmentedControl的简单使用

               

  •  选项卡控件,同一时刻只能选中一个标签

1.     设置标签的个数

  •    storyboard

 

  •    代码

代码中只能在创建UISegmentControl的同时初始化所有的标签

 

NSArray *items = @[@"2列", @"3列", @"4列"];

UISegmentedControl *control = [[UISegmentedControl alloc] initWithItems:items];

2.     设置每个标签显示的文字内容

  •    storyboard

 

  •    代码

 

[control setTitle:@"2列" forSegmentAtIndex:0];

3.     获得当前被选中的标签位置

 

int index = control.selectedSegmentIndex;

4.     监听事件

监听UISegmentControl的改变,应该用Value Changed事件(参照UISlider的使用)

 


 示例:

主要是利用selectedSegmentIndex的属性的值的不同

对UISegmentedControl进行事件监听 实现如下所示的图片排列 

               

代码如下:

//
//  WHBLAPViewController.h
//  05-UISegmentControl简单使用
//
//  Created by whblap on 14-6-12.
//  Copyright (c) 2014年 whblap. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface WHBLAPViewController : UIViewController
- (IBAction)indexChange:(UISegmentedControl *)sender;

@end
WHBLAPViewController.h
//
//  WHBLAPViewController.m
//  05-UISegmentControl简单使用
//
//  Created by whblap on 14-6-12.
//  Copyright (c) 2014年 whblap. All rights reserved.
//

#import "WHBLAPViewController.h"
// 图片的宽高度
#define ImgWH 50

@interface WHBLAPViewController ()

@end

@implementation WHBLAPViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setImgPosWithcoloums:2 andAdd:YES];
}

- (IBAction)indexChange:(UISegmentedControl *)sender
{
    [UIView beginAnimations:Nil context:nil];
    [UIView setAnimationDuration:0.5];
    [self setImgPosWithcoloums:sender.selectedSegmentIndex+2 andAdd:NO];
     [UIView commitAnimations];
}
#pragma mark  设置图片位置 列数 是否自动添加图片
- (void)setImgPosWithcoloums:(int)coloum andAdd:(int)add
{
    // 1.定义列数
    int coloums = coloum;
    //  设置图片间距  图片间距=(总界面视图宽度-图片x轴宽度大小*列数)/ 列数+1;
    CGFloat margin = (self.view.frame.size.width - ImgWH*coloums)/(coloums+1);
    
    // 2.设置第一个图片的位置
    int oneX = margin; // 第一个位置为其图片间的宽度
    int oneY = 80;
    
    for (int i = 0; i < 9; i++) {
        // 3.设置第i个图片对应列的位置 列数(col)决定了x
        int col = (i%coloums);  
        CGFloat x = oneX + col*(ImgWH + margin);
        
        // 设置第i个图片对应行的位置
        int row = (i/coloums);
        CGFloat y = oneY + row*(ImgWH + margin);
        
        if (add) {
            // 创建图片
            UIImageView *imageView = [[UIImageView alloc] init];
            NSString *imageNames = [NSString stringWithFormat:@"01%d.png",i];
            imageView.image = [UIImage imageNamed:imageNames];
            // 设置图片的位置 及 宽高
            imageView.frame = CGRectMake(x, y, ImgWH,ImgWH);
            // 将子视图添加到视图中
            [self.view addSubview:imageView];
        }
        else
        {
            // 更改每个图片的视图的位置
            UIView *sub = self.view.subviews[i+1];
            NSLog(@"%@",sub.class);
            sub.frame = CGRectMake(x, y, ImgWH, ImgWH);
        }
    }
}
@end
WHBLAPViewController.m

 

 

posted on 2014-06-14 11:59  ゴルツの惠斌纳閣下  阅读(327)  评论(0编辑  收藏  举报