码迷,mamicode.com
首页 > 其他好文 > 详细

Coding日志

时间:2015-08-11 12:07:20      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

1:UITextField设置出现清除按键:

self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;

说明:

UITextField.clearButtonMode:清空输入的字符,有以下几种模式
UITextFieldViewModeAlways,不为空,获得焦点与没有获得焦点都显示清空按钮
UITextFieldViewModeNever,不显示清空按钮
UITextFieldViewModeWhileEditing,不为空,且在编辑状态时(及获得焦点)显示清空按钮
UITextFieldViewModeUnlessEditing, 不为空,且不在编译状态时(焦点不在输入框上)显示清空按钮

扩展:关于键盘类型(UITextField.keyboardType),UITextField.enablesReturnKeyAutomatically = YES当UITextField不为空时高亮,[UITextField ResignFirstResponder]关闭键盘

2.绘画一条下划线:

通过一个视图,定义其位置跟背景就可以,下面代码仅供参考
         self.backgroundView = nil;
         self.backgroundColor = [UIColor clearColor];
         UIView* _lineView = [[UIView alloc] initWithFrame:CGRectMake(kInput_OnlyText_Cell_LeftPading, 43.5, kScreen_Width-2*kInput_OnlyText_Cell_LeftPading, 0.5)];
        _lineView.backgroundColor = [UIColor colorWithHexString:@"0xaebdc9"];
        [self.contentView addSubview:_lineView];
        

3:表格一些设置:

   self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;//不加换行线
    self.myTableView.backgroundColor = [UIColor colorWithHexString:@"0xfafafa"];
    UIView *upBgView = [[UIView alloc] initWithFrame:self.view.bounds];
    upBgView.backgroundColor =[UIColor colorWithHexString:@"0x29333f"];
    [upBgView setY:-CGRectGetHeight(upBgView.bounds)];
    [self.myTableView addSubview:upBgView];
    
    self.myTableView.contentInset = UIEdgeInsetsMake(-kHigher_iOS_6_1_DIS(20), 0, 0, 0);//缩进
    self.myTableView.tableFooterView=[self customFooterView];//方法 返回view,看第五点
    self.myTableView.tableHeaderView = [self customHeaderView];

扩展:

UITableViewCellSelectionStyle选择行的样式UITableViewCellSelectionStyleNone,UITableViewCellSelectionStyleBlue,UITableViewCellSelectionStyleGray
如果要自定义cell的背景色
cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:cell.frame]];
cell.selectedBackgroundView.backgroundColor = [UIColor redColor];

改变换行线颜色 tableView.separatorColor = [UIColor blueColor];

4:可以定义表头跟底部视图(代码接上面):

- (UIView *)customHeaderView{
    UIView *headerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 180)];
    UIImageView *loginLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_logo"]];
    CGFloat loginLogoHeight = CGRectGetHeight(loginLogo.bounds)*kScreen_Width/CGRectGetWidth(loginLogo.bounds);
    if (loginLogoHeight > 180) {
        [headerV setHeight:loginLogoHeight];
    }
    loginLogo.frame = CGRectMake(0, 0, kScreen_Width, loginLogoHeight);
    [headerV addSubview:loginLogo];

    return headerV;
}
- (UIView *)customFooterView{
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 100)];
    _loginBtn = [UIButton buttonWithStyle:StrapSuccessStyle andTitle:@"登录" andFrame:CGRectMake(18, kScreen_Width > 320? 20: 20, kScreen_Width-18*2, 45) target:self action:@selector(sendLogin)];
    [footerV addSubview:_loginBtn];
    return footerV;
}

5:隐藏本页的导航栏:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES];

}

6、活动指示器UIActivityIndicatorView:

可以告知用户有一个操作正在进行中。派生自UIView,所以他是视图,也可以附着在视图上。
UIActivityIndicatorView* activityIndicatorView = [ [ UIActivityIndicatorView alloc ]?initWithFrame:CGRectMake(250.0,20.0,30.0,30.0)];
设置风格:
activityIndicatorView.activityIndicatorViewStyle= UIActivityIndicatorViewStyleGray;
UIActivityIndicatorViewStyleWhiteLarge 大型白色指示器
UIActivityIndicatorViewStyleWhite 标准尺寸白色指示器
UIActivityIndicatorViewStyleGray 灰色指示器,用于白色背景
如果希望指示器停止后自动隐藏,那么要设置hidesWhenStoped属性为YES。默认是YES。设置为NO停止后指示器仍会显示。activityIndicatorView.hidesWhenStoped = NO;
显示:可以将它附着在任何视图上,比如表格单元、或者视图,[ self.view addSubview:activityIndicatorView ]

启动和停止
[ activityIndicatorView startAnimating ];//启动
[ activityIndicatorView stopAnimating ];//停止

判断是否处于运动状态isAnimating
[activityIndicatorView isAnimating]

下面为一段实例代码
_activityIndicator = [[UIActivityIndicatorView alloc]
                                 initWithActivityIndicatorStyle:
                                 UIActivityIndicatorViewStyleGray];
            CGSize captchaViewSize = _captchaView.bounds.size;
            _activityIndicator.hidesWhenStopped = YES;
            [_activityIndicator setCenter:CGPointMake(captchaViewSize.width/2, captchaViewSize.height/2)];
            [_captchaView addSubview:_activityIndicator];

7.使用NSUserDefaults保存用户名和密码:

创建一个user defaults方法有多个,最简单得快速创建方法:
NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];

添加数据到 user defaults:
[accountDefaults setObject:nameField.text forKey:UserDefaultNameKey];

也可以添加基本数据类型int, float, bool等,有相应得方法
[accountDefaults setBool:YES forKey:UserDefaultBoolKey];

从user defaults中获取数据:
[accountDefaults objectForKey:NCUserDefaultNameKey]  
[accountDefaults boolForKey: UserDefaultBoolKey];

注意:UserDefaults不是立即写入,而是根据时间戳定时的把缓存中的数据写入本地磁盘。所以调用了set方法之后数据有可能还没有写入磁盘应用程序就终止了。可以通过调用synchornize方法强制写入。[[NSUserDefaults standardUserDefaults] synchronize]; 

代码片段:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:[NSNumber numberWithBool:YES] forKey:kLoginStatus];
        [defaults setObject:loginData forKey:kLoginUserDict];
        [defaults synchronize];

UITableviewcell的accessoryType属性:

cell.accessoryType = UITableViewCellAccessoryNone;//cell没有任何的样式  
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头,距离右边有十几像素;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;//cell右边有一个蓝色的圆形button; 
cell.accessoryType = UITableViewCellAccessoryCheckmark;//cell右边的形状是对号;

导航栏的按键(自定义图片):

UIButton *settingBtn = [self navButtonWithImageName:@"settingBtn_Nav" action:@selector(settingBtnClicked:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:settingBtn];
    
    UIButton *addUserBtn = [self navButtonWithImageName:@"addUserBtn_Nav" action:@selector(addUserBtnClicked:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addUserBtn];

自定义表格行(继承UITableViewCell):

@interface TitleRImageMoreCell ()
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UIImageView *userIconView;
@end
@implementation TitleRImageMoreCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        if (!_titleLabel) {
            _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kPaddingLeftWidth, ([TitleRImageMoreCell cellHeight] -30)/2, 100, 30)];
            _titleLabel.backgroundColor = [UIColor clearColor];
            _titleLabel.font = [UIFont systemFontOfSize:16];
            _titleLabel.textColor = [UIColor blackColor];
            [self.contentView addSubview:_titleLabel];
        }
        if (!_userIconView) {
            _userIconView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreen_Width- kTitleRImageMoreCell_HeightIcon)- kPaddingLeftWidth- 30, ([TitleRImageMoreCell cellHeight] -kTitleRImageMoreCell_HeightIcon)/2, kTitleRImageMoreCell_HeightIcon, kTitleRImageMoreCell_HeightIcon)];
            [_userIconView doCircleFrame];
            [self.contentView addSubview:_userIconView];
        }
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    if (!_curUser) {
        return;
    }
    self.titleLabel.text = @"头像";
    [self.userIconView sd_setImageWithURL:[_curUser.avatar urlImageWithCodePathResizeToView:_userIconView] placeholderImage:kPlaceholderMonkeyRoundView(_userIconView)];
}

+ (CGFloat)cellHeight{
    return 70.0;
}

@end

然后进行调用时(可以属性传值,并在不同的地方加载不同的行及其高度):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        TitleRImageMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleRImageMore forIndexPath:indexPath];
        cell.curUser = _curUser;
        [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:kPaddingLeftWidth];
        return cell;
}
else
{
TitleValueMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleValueMore forIndexPath:indexPath];
}
return cell;
}

当给按键的图标进行方向改变:

[self setImage:[UIImage imageNamed:@"nav_arrow_down"] forState:UIControlStateNormal];
self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, DEGREES_TO_RADIANS(180));//这这是进行180度转到,向下或向下

在导航栏中间增加一个带图片文字的控件:

- (UIDownMenuButton *)initWithTitles:(NSArray *)titleList andDefaultIndex:(NSInteger)index andVC:(UIViewController *)viewcontroller{
    self = [super init];
    if (self) {
        _titleList = titleList;
        _curIndex = index;
        _curShowing = NO;
        _mySuperView = viewcontroller.view;
        
        self.backgroundColor = [UIColor clearColor];
        [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        [self.titleLabel setFont:[UIFont systemFontOfSize:kNavTitleFontSize]];
        [self.titleLabel setMinimumScaleFactor:0.5];
        [self addTarget:self action:@selector(changeShowing) forControlEvents:UIControlEventTouchUpInside];
        [self refreshSelfUI];
    }
    return self;
}

- (void)refreshSelfUI{
    NSString *titleStr = @"";
    DownMenuTitle *menuObj = [self.titleList objectAtIndex:self.curIndex];
    titleStr = menuObj.titleValue;
    CGFloat titleWidth = [titleStr getWidthWithFont:self.titleLabel.font constrainedToSize:CGSizeMake(kScreen_Width, 30)];//获得文字的宽度
    CGFloat btnWidth = titleWidth +kNavImageWidth;
    self.frame = CGRectMake((kScreen_Width-btnWidth)/2, (44-30)/2, btnWidth, 30);

    self.titleEdgeInsets = UIEdgeInsetsMake(0, -kNavImageWidth, 0, kNavImageWidth);
    self.imageEdgeInsets = UIEdgeInsetsMake(0, titleWidth, 0, -titleWidth);
    [self setTitle:titleStr forState:UIControlStateNormal];
    [self setImage:[UIImage imageNamed:@"nav_arrow_down"] forState:UIControlStateNormal];
}

其中几个值:

#define  kNavTitleFontSize 19
#define kScreen_Width [UIScreen mainScreen].bounds.size.width
#define kNavImageWidth (15.0+5.0)

然后直接赋给titleview:

    UIDownMenuButton *navBtn = [[UIDownMenuButton alloc] initWithTitles:titleList andDefaultIndex:index andVC:self];
    navBtn.menuIndexChanged = block;
    self.navigationItem.titleView = navBtn;

注意:button都是有带文字跟图片的,只是图片都是在左边,要通过uiedgeinsetsmake对图片跟文字进行位置的改变。可以在导航栏的titleview做文章,放一些其它控件,或视图;

集合视图UICollectionView的简单使用:

要遵循三个协议:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout

设置单元格的布局
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
[flowLayout setItemSize:CGSizeMake(70, 100)];//设置cell的尺寸
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];//设置其布局方向
flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);//设置其边界
//其布局很有意思,当你的cell设置大小后,一行多少个cell,由cell的宽度决定

然后设置集合视图:
_collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height) collectionViewLayout:flowLayout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    [_collectionView registerClass:[BMCollectionCell class] forCellWithReuseIdentifier:CELL_ID];
    [self.view addSubview:_collectionView];

注意:其它委托事件没全写出,比如numberOfSectionsInCollectionView等;

CALayer常见几个设置:

边框,圆角,阴影
设置圆角边框
?someView.layer.cornerRadius =4.0f;
someView.layer.masksToBounds = YES;
//设置边框及边框颜色
?someView.layer.borderWidth = 0.5f;
someView.layer.borderColor =[ [UIColor grayColor] CGColor];
?//添加四个边阴影? _imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;? _imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);?  _imgvPhoto.layer.shadowOpacity = 0.5;? _imgvPhoto.layer.shadowRadius = 10.0;
 _ imgvPhoto.layer.masksToBounds = NO;
  //添加两个边阴影?    _imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;?    _imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);?    _imgvPhoto.layer.shadowOpacity = 0.5;?    _imgvPhoto.layer.shadowRadius = 2.0;
说明:?①     someView  表示UIView及其之类;?②     
必须引入:#import<QuartzCore/QuartzCore.h>

UIActionSheet弹出显示:

#define kKeyWindow [UIApplication sharedApplication].keyWindow
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
[actionSheet showInView:kKeyWindow];

block回调传参的运用:

有两个viewcontroller分别为a,b;其中a跳转到b,从b得到一个值,然后再跳转到a,并显示出b的值;
代码如下:
a.h
- (IBAction)otherStoryboard:(id)sender;
@property (weak, nonatomic) IBOutlet UILabel *lableInfo;

a.m

- (IBAction)otherStoryboard:(id)sender {
    UIStoryboard* mainStoryboard=[UIStoryboard storyboardWithName:@"HotelStoryboard" bundle:nil];
    HotelViewController* weathcontroller=[mainStoryboard instantiateViewControllerWithIdentifier:@"hotelStoryboard"];
    weathcontroller.block=^(NSString* InputValue)
    {
        self.lableInfo.text=InputValue;
    };
    [self presentViewController:weathcontroller animated:YES completion:^{
        
    }];
}

b.h
typedef void(^ChangInputText)(NSString* InputValue);
@property(copy,nonatomic)ChangInputText block;
- (IBAction)backButton:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *inputText;

b.m
- (IBAction)backButton:(id)sender {
    NSString* backsValue=self.inputText.text;
    _block(backsValue);
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

当然也可以使用一个公开的方法,然后把block伟参数直接调用,可以访问下面的网址:
http://blog.csdn.net/itpeng523/article/details/24315541

单例模式运用:

.h

@interface Coding_NetAPIManager : NSObject
(instancetype)sharedManager;

- (void)request_Tweet_DoTweet_WithObj:(Tweet *)tweet andBlock:(void (^)(id data, NSError *error))block;
@end

.m

@implementation Coding_NetAPIManager
+ (instancetype)sharedManager {
    static Coding_NetAPIManager *shared_manager = nil;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        shared_manager = [[self alloc] init];
    });
    return shared_manager;
}

(void)request_Tweet_DoTweet_WithObj:(Tweet *)tweet andBlock:(void (^)(id data, NSError *error))block{    ….   }
@end


然后调用时:
        [[Coding_NetAPIManager sharedManager] request_Tweet_DoTweet_WithObj:nextTweet andBlock:^(id data, NSError *error) {

        }];

字符串显示问题,同一行不同的效果:

调用:
[_fansCountBtn setAttributedTitle:[self getStringWithTitle:@"粉丝" andValue:_curUser.fans_count.stringValue] forState:UIControlStateNormal];

方法:
- (NSMutableAttributedString*)getStringWithTitle:(NSString *)title andValue:(NSString *)value{
    NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ %@", value, title]];
    [attriString addAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:17],
                                 NSForegroundColorAttributeName : [UIColor whiteColor]}
                         range:NSMakeRange(0, value.length)];
    
    [attriString addAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14],
                                 NSForegroundColorAttributeName : [UIColor whiteColor]}
                         range:NSMakeRange(value.length+1, title.length)];
    return  attriString;
}

另:label可以调用sizeToFit来调整内容适应

_userLabel.text = _curUser.name;
[_userLabel sizeToFit];

日期控件ActionSheetDatePicker  多级控件ActionSheetStringPicker:

小实例:
                    NSDate *curDate = [NSDate dateFromString:_curUser.birthday withFormat:@"yyyy-MM-dd"];
                    if (!curDate) {
                        curDate = [NSDate dateFromString:@"1990-01-01" withFormat:@"yyyy-MM-dd"];
                    }
                    ActionSheetDatePicker *picker = [[ActionSheetDatePicker alloc] initWithTitle:nil datePickerMode:UIDatePickerModeDate selectedDate:curDate doneBlock:^(ActionSheetDatePicker *picker, NSDate *selectedDate, id origin) {
                        NSString *preValue = weakSelf.curUser.birthday;
                        weakSelf.curUser.birthday = [selectedDate string_yyyy_MM_dd];
                        [weakSelf.myTableView reloadData];
                        [[Coding_NetAPIManager sharedManager] request_UpdateUserInfo_WithObj:weakSelf.curUser andBlock:^(id data, NSError *error) {
                            if (data) {
                                weakSelf.curUser = data;
                            }else{
                                weakSelf.curUser.birthday = preValue;
                            }
                            [weakSelf.myTableView reloadData];
                        }];
                    } cancelBlock:^(ActionSheetDatePicker *picker) {
                        NSLog(@"%@", picker.description);
                    } origin:self.view];
                    picker.minimumDate = [[NSDate date] offsetYear:-120];
                    picker.maximumDate = [NSDate date];
                    [picker showActionSheetPicker];

小实例:

[ActionSheetStringPicker showPickerWithTitle:nil rows:@[[AddressManager firstLevelArray], [AddressManager secondLevelMap]] initialSelection:@[firstLevel, secondLevel] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                        NSString *preValue = weakSelf.curUser.location;
                        NSString *location = [selectedValue componentsJoinedByString:@" "];
                        weakSelf.curUser.location = location;
                        [weakSelf.myTableView reloadData];
                        [[Coding_NetAPIManager sharedManager] request_UpdateUserInfo_WithObj:weakSelf.curUser andBlock:^(id data, NSError *error) {
                            if (data) {
                                weakSelf.curUser = data;
                            }else{
                                weakSelf.curUser.location = preValue;
                            }
                            [weakSelf.myTableView reloadData];
                        }];
                    } cancelBlock:nil origin:self.view];

小实例:

[ActionSheetStringPicker showPickerWithTitle:nil rows:@[@[@"", @"", @"未知"]] initialSelection:@[_curUser.sex] doneBlock:^(ActionSheetStringPicker *picker, NSArray * selectedIndex, NSArray *selectedValue) {
                        NSNumber *preValue = weakSelf.curUser.sex;
                        weakSelf.curUser.sex = [selectedIndex firstObject];
                        [weakSelf.myTableView reloadData];
                        [[Coding_NetAPIManager sharedManager] request_UpdateUserInfo_WithObj:weakSelf.curUser andBlock:^(id data, NSError *error) {
                            if (data) {
                                weakSelf.curUser = data;
                            }else{
                                weakSelf.curUser.sex = preValue;
                            }
                            [weakSelf.myTableView reloadData];
                        }];
                    } cancelBlock:nil origin:self.view];

统一修改导航栏的样式,在 AppDelegate.m中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    //设置导航条样式
    [self customizeInterface];
    
    if ([Login isLogin]) {
        [self setupTabViewController];
    }else{
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        [self setupLoginViewController];
    }
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)customizeInterface {
    //设置Nav的背景色和title色
    UINavigationBar *navigationBarAppearance = [UINavigationBar appearance];
    NSDictionary *textAttributes = nil;
    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        [navigationBarAppearance setTintColor:[UIColor whiteColor]];//返回按钮的箭头颜色
        [[UITextField appearance] setTintColor:[UIColor colorWithHexString:@"0x3bbc79"]];//设置UITextField的光标颜色
        [[UITextView appearance] setTintColor:[UIColor colorWithHexString:@"0x3bbc79"]];//设置UITextView的光标颜色
        [[UISearchBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"0xe5e5e5"]] forBarPosition:0 barMetrics:UIBarMetricsDefault];

        textAttributes = @{
                           NSFontAttributeName: [UIFont boldSystemFontOfSize:kNavTitleFontSize],
                           NSForegroundColorAttributeName: [UIColor whiteColor],
                           };
    } else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0
        [[UISearchBar appearance] setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"0xe5e5e5"]]];

        textAttributes = @{
                           UITextAttributeFont: [UIFont boldSystemFontOfSize:kNavTitleFontSize],
                           UITextAttributeTextColor: [UIColor whiteColor],
                           UITextAttributeTextShadowColor: [UIColor clearColor],
                           UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetZero],
                           };
#endif
    }
    [navigationBarAppearance setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:@"0x28303b"]] forBarMetrics:UIBarMetricsDefault];
    [navigationBarAppearance setTitleTextAttributes:textAttributes];
}

其中上面的版本判断:

FOUNDATION_EXPORT double NSFoundationVersionNumber;

#if TARGET_OS_IPHONE
#define NSFoundationVersionNumber_iPhoneOS_2_0    678.24
#define NSFoundationVersionNumber_iPhoneOS_2_1  678.26
#define NSFoundationVersionNumber_iPhoneOS_2_2  678.29
#define NSFoundationVersionNumber_iPhoneOS_3_0  678.47
#define NSFoundationVersionNumber_iPhoneOS_3_1  678.51
#define NSFoundationVersionNumber_iPhoneOS_3_2  678.60
#define NSFoundationVersionNumber_iOS_4_0  751.32
#define NSFoundationVersionNumber_iOS_4_1  751.37
#define NSFoundationVersionNumber_iOS_4_2  751.49
#define NSFoundationVersionNumber_iOS_4_3  751.49
#define NSFoundationVersionNumber_iOS_5_0  881.00
#define NSFoundationVersionNumber_iOS_5_1  890.10
#define NSFoundationVersionNumber_iOS_6_0  992.00
#define NSFoundationVersionNumber_iOS_6_1  993.00
#define NSFoundationVersionNumber_iOS_7_0 1047.20
#define NSFoundationVersionNumber_iOS_7_1 1047.25
#endif

弹出一个视图,并有一个背影的视图(大体代码):

- (UIView *)myTapBackgroundView{
    if (!_myTapBackgroundView) {
        _myTapBackgroundView = ({
            UIView *view = [[UIView alloc] initWithFrame:kScreen_Bounds];
            view.backgroundColor = [UIColor clearColor];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeShowing)];
            [view addGestureRecognizer:tap];
            view;
        });
    }
    return _myTapBackgroundView;
}

- (UIView *)myContentView{
    if (!_myContentView) {
        _myContentView = ({
            UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
            view.backgroundColor = [UIColor whiteColor];
            view;
        });
    }
    return _myContentView;
}

- (void)changeShowing{
    [kKeyWindow endEditing:YES];
    if (!_myContentView) {//未载入过
        [self loadUIElement];
    }
    CGPoint origin = [self convertPoint:CGPointZero toView:kKeyWindow];
    CGFloat contentHeight = self.isShowing? 0: kCodeBranchTagButton_ContentHeight;
    if (self.isShowing) {//隐藏
        self.enabled = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.myTapBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
            self.myContentView.alpha = 0;
            self.myContentView.frame = CGRectMake(0, origin.y-contentHeight, kScreen_Width, contentHeight);
            self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, DEGREES_TO_RADIANS(180));
        } completion:^(BOOL finished) {
            [self.myTapBackgroundView removeFromSuperview];
            [self.myContentView removeFromSuperview];
            self.enabled = YES;
            self.isShowing = NO;
        }];
    }else{//显示
        self.myContentView.frame = CGRectMake(0, origin.y, kScreen_Width, 0);
        [kKeyWindow addSubview:self.myTapBackgroundView];
        [kKeyWindow addSubview:self.myContentView];
        self.enabled = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.myTapBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
            self.myContentView.alpha = 1.0;
            self.myContentView.frame = CGRectMake(0, origin.y-contentHeight, kScreen_Width, contentHeight);
            self.imageView.transform = CGAffineTransformRotate(self.imageView.transform, DEGREES_TO_RADIANS(180));
        } completion:^(BOOL finished) {
            self.enabled = YES;
            self.isShowing = YES;
        }];
    }
}

其中:#define kScreen_Bounds [UIScreen mainScreen].bounds
#define kKeyWindow [UIApplication sharedApplication].keyWindow

运用在项目中一个下拉菜单:

/**

 *  @author wujunyang, 15-05-13 14:05:12

 *

 *  @brief  初始化背景视图

 *  @return <#return value description#>

 */

- (UIView *)myTapBackgroundView{

    if (!_myTapBackgroundView) {

        _myTapBackgroundView = ({

            UIView *view = [[UIView alloc] initWithFrame:SCREENFRAME];

            view.backgroundColor = [UIColor clearColor];

            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeShowing)];

            [view addGestureRecognizer:tap];

            view;

        });

    }

    return _myTapBackgroundView;

}

/**

 *  @author wujunyang, 15-05-13 14:05:25

 *

 *  @brief  初始化弹出视图

 *  @return <#return value description#>

 */

- (UIView *)myContentView{

    if (!_myContentView) {

        _myContentView = ({

            UIView *view = [[UIView alloc] initWithFrame:CGRectZero];

            view.backgroundColor = [UIColor whiteColor];

            view;

        });

    }

    return _myContentView;

}

/**

 *  @author wujunyang, 15-05-13 14:05:39

 *

 *  @brief  加载xib文件到弹出视图里面

 */

- (void)loadUIElement{

    self.myTapBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];

    self.homeMyselfMenuView=[HomeMyselfMenuView instanceHomeMyselfMenuView];

    self.homeMyselfMenuView.frame = CGRectMake(0, 0, 0, 0);//注意其宽高

    [self.myContentView addSubview:self.homeMyselfMenuView];

}

/**

 *  @author wujunyang, 15-05-13 14:05:07

 *

 *  @brief  控制视图的显示及隐藏

 */

- (void)changeShowing{

    if (!_myContentView) {

        [self loadUIElement];

    }

    CGFloat contentHeight = self.isShowing? 0: STATUSNAVBARHEIGHT;

    if (self.isShowing) {//隐藏

        [self narrowTransToView:NO];

        [UIView animateWithDuration:0.3 animations:^{

            self.myTapBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];

            self.myContentView.alpha = 0;

            self.myContentView.frame = CGRectMake(0,0, SCREEN_WIDTH, contentHeight);

        } completion:^(BOOL finished) {

            [self.myTapBackgroundView removeFromSuperview];

            [self.myContentView removeFromSuperview];

            self.isShowing = NO;

        }];

    }else{//显示

        [self narrowTransToView:YES];

        self.myContentView.frame = CGRectMake(0, STATUSNAVBARHEIGHT, SCREEN_WIDTH, 0);

        [self.view addSubview:self.myTapBackgroundView];

        [self.view addSubview:self.myContentView];

        [UIView animateWithDuration:0.3 animations:^{

            self.myTapBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];

            self.myContentView.alpha = 1.0;

            self.myContentView.frame = CGRectMake(0, STATUSNAVBARHEIGHT, SCREEN_WIDTH, contentHeight);

        } completion:^(BOOL finished) {

            self.isShowing = YES;

        }];

    }

}

/**

 *  @author wujunyang, 15-05-13 15:05:22

 *

 *  @brief  视图区缩放

 *  @param isNarrow 是否缩放

 */

-(void)narrowTransToView:(BOOL)isNarrow

{

    _contentView.transform=CGAffineTransformIdentity;

    [UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];

    if(isNarrow)

    {

    _contentView.transform=CGAffineTransformMakeScale(0.9f, 0.9f);

    }

    else

    {

        _contentView.transform=CGAffineTransformMakeScale(1.0f, 1.0f);

    }

    [UIView commitAnimations];

}

 

Coding日志

标签:

原文地址:http://www.cnblogs.com/xiguain/p/4720441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!