UIButton详解及怎么着调节image和title的布局,图片部分截图

By admin in 美高梅手机版4858 on 2019年8月17日

[iOS UI进阶,iosui进阶

A.需求 1.优化品种设置 2.自定义导航栏标题开关 3.多版本处理4.iOS6和iOS7的适配 5.装置开关背景 6.设置值UIBarButtonItem样式  
B.实现 1.种类配置 (1)程序运转时期遮盖状态栏 1 –
(BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 2 //
Override point for customization after application launch. 3 4 //
设置情形栏样式为暗紫 5 application.statusBarHidden = NO; 6
application.statusBarStyle = UIStatusBarStyleLightContent; 7 8 return
YES; 9 }   (3)撤销渲染appLogo(撤废系统渲染效果) 1 // 2 //
TitleExtendButton.m 3 // HelloLottery 4 // 5 // Created by
hellovoidworld on 15/54%. 6 // Copyright (c) 2016年 hellovoidworld. All
rights reserved. 7 // 8 9 #import “TitleExtendButton.h” 10 11
@interface TitleExtendButton() 12 13 @property(nonatomic, strong) UIFont
*titleFont; 14 15 @end 16 17 @implementation TitleExtendButton 18 19
/** 从文件加载对象就会调用此方法,比如xib和storybard */ 20 –
(id)initWithCoder:(NSCoder *)aDecoder { 21
NSLog(@”从文件加载TitleButton”); 22 if (self = [super
initWithCoder:aDecoder]) { 23 [self initializeButton]; 24 } 25 26
return self; 27 } 28 29 /** 从代码中加载对象就会调用此方法 */ 30 –
(instancetype)initWithFrame:(CGRect)frame { 31
NSLog(@”从代码加载TitleButton”); 32 if (self = [super
initWithFrame:frame]) { 33 [self initializeButton]; 34 } 35 36 return
self; 37 } 38 39 – (void) initializeButton { 40 // 设置font 41
self.titleFont = [UIFont systemFontOfSize:14]; // 一时半刻先自定义font 42
self.titleLabel.font = self.titleFont; 43 44 // Logo居中 45
[self.imageView setContentMode:UIViewContentModeCenter]; 46 } 47 48 49
/** 返回title的frame */ 50 –
(CGRect)titleRectForContentRect:(CGRect)contentRect { 51 CGFloat titleX
= 0; 52 CGFloat titleY = 0; 53 54 NSDictionary *attr =
@{NSFontAttributeName : self.titleFont}; 55 CGFloat titleWidth; 56 57 //
唯有 iOS7 版本以上才具运维以下代码 58 if (iOS7) { 59 // 独有 Xcode5
或上述版本技艺辨别这段代码 60 #ifdef __IPHONE_7_0 61 titleWidth =
[self.currentTitle boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin attributes:attr
context:nil].size.width; 62 #else 63 titleWidth = [self.currentTitle
sizeWithFont:self.titleFont].width; 64 #endif 65 } else { //
不然使用旧的API 66 titleWidth = [self.currentTitle
sizeWithFont:self.titleFont].width; 67 } 68 69 CGFloat titleHeight =
contentRect.size.height; 70 71 return CGRectMake(titleX, titleY,
titleWidth, titleHeight); 72 } 73 74 /** 返回image的frame */ 75 –
(CGRect)imageRectForContentRect:(CGRect)contentRect { 76 CGFloat
imageWidth = 30; 77 CGFloat imageHeight = contentRect.size.height; 78
CGFloat imageX = contentRect.size.width – imageWidth; 79 CGFloat imageY
= 0; 80 return CGRectMake(imageX, imageY, imageWidth, imageHeight); 81 }
82 83 @end   1 // 2 // HVWBuyViewController.m 3 // HelloLottery 4 // 5
// Created by hellovoidworld on 15/1/3. 6 // Copyright (c) 2015年
hellovoidworld. All rights reserved. 7 // 8 9 #import
“HVWBuyViewController.h” 10 #import “TitleExtendButton.h” 11 12
@interface HVWBuyViewController () 13 14 @property(nonatomic, weak)
UIView *popupView; 15 16 /** 标题点击事件 */ 17 –
(IBAction)titleClicked:(TitleExtendButton *)sender; 18 19 @end 20 21
@implementation HVWBuyViewController 22 23 – (void)viewDidLoad { 24
[super viewDidLoad]; 25 // Do any additional setup after loading the
view. 26 27 } 28 29 – (void)didReceiveMemoryWarning { 30 [super
didReceiveMemoryWarning]; 31 // Dispose of any resources that can be
recreated. 32 } 33 34 /** 延迟开首化弹出view 35 *
(开掘位于viewDidLoad的时候,在点击开关调用的时候pupupView的frame未有被初步化)
36 */ 37 – (UIView *)popupView { 38 if (_popupView == nil) { 39 //
开始化弹出view 40 UIView *popupView = [[UIView alloc] init]; 41
CGFloat popupViewX = 0; 42 CGFloat popupViewY = [UIApplication
sharedApplication].statusBarFrame.size.height +
self.navigationController.navigationBar.frame.size.height; 43 CGFloat
popupViewWidth =
self.navigationController.navigationBar.frame.size.width; 44 CGFloat
popupViewHeight = self.view.frame.size.height – popupViewY –
self.tabBarController.tabBar.frame.size.height; 45 popupView.frame =
CGRectMake(popupViewX, popupViewY, popupViewWidth, popupViewHeight); 46
popupView.backgroundColor = [UIColor grayColor]; 47 48 UILabel *label
= [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 100)]; 49
label.text = @”那是任何彩种de弹出内容”; 50 [popupView
addSubview:label]; 51 52 self.popupView = popupView; 53 NSLog(@”%@”,
NSStringFromCGRect(self.popupView.frame)); 54 } 55 56 return
_popupView; 57 } 58 59 /** 标题点击事件 60 * 转变箭头方向 61 *
伸缩内容 62 */ 63 – (IBAction)titleClicked:(TitleExtendButton *)sender
{ 64 [UIView animateWithDuration:0.5 animations:^{ 65 // 开关旋转 66
sender.imageView.transform =
CGAffineTransformRotate(sender.imageView.transform, M_PI); 67 }]; 68
69 // 弹出view 70 if (![self.popupView isDescendantOfView:self.view])
{ 71 [self.view addSubview:self.popupView]; 72 } else { 73
[self.popupView removeFromSuperview]; 74 } 75 } 76 @end   1 #define
__IPHONE_2_0 20000 2 #define __IPHONE_2_1 20100 3 #define
__IPHONE_UIButton详解及怎么着调节image和title的布局,图片部分截图。2_2 20200 4 #define __IPHONE_3_0 30000 5 #define
__IPHONE_3_1 30100 6 #define __IPHONE_3_2 30200 7 #define
__IPHONE_4_0 40000 8 #define __IPHONE_4_1 40100 9 #define
__IPHONE_4_2 40200 10 #define __IPHONE_4_3 40300 11 #define
__IPHONE_5_0 50000 12 #define __IPHONE_5_1 50100 13 #define
__IPHONE_6_0 60000 14 #define __IPHONE_6_1 60100 15 #define
__IPHONE_7_0 70000 16 #define __IPHONE_7_1 70100 17 #define
__IPHONE_8_0 80000 18 #define __IPHONE_8_1 80100   6.iOS6 和
iOS7 的轻易适配

由于iOS6及前边的本子,显示器view的岗位尺寸是索要去掉状态栏、导航栏等的职分尺寸的
而iOS7及随后的本子,显示屏view的职位尺寸暗许是挤占了上上下下显示器这里须要设置iOS6 和 iOS7, 调整view的frame坐标原点都以完全一样的 (1)iOS7
中 view的扩张效果
iOS7其实是增加了一个扩充属性,技艺将荧屏view扩充到全屏幕由于不是TableController也许ScrollController的view无需滚动,所以不须要进行扩充增加属性:self.edgesForExtendedLayout  
在storyboard修改扩张属性,撤废扩大,默许使用iOS6的做法: 修改调整器的性能1 // 2 // UIImage+Extend.m 3 // HelloLottery 4 // 5 // Created by
hellovoidworld on 15/51%. 6 // Copyright (c) 二零一四年 hellovoidworld. All
rights reserved. 7 // 8 9 #import “UIImage+Extend.h” 10 11
@implementation UIImage(Extend) 12 13 /** 再次回到三个着力扩大拉伸的图形
*/ 14 + (UIImage *) resizableImage:(NSString *) imageName { 15
UIImage *image = [UIImage imageNamed:imageName]; 16 17 //
这一个参数决定了右手的护卫区域,侧边的保卫安全区域为侧面+1开端到前边 18
CGFloat width = image.size.width * 0.5; 19 20 // 法规同左右掩护区域 21
CGFloat height = image.size.height * 0.5; 22 23 //
相当于,取中间1×1的区域作为扩展区域 24 return [image
stretchableImageWithLeftCapWidth:width topCapHeight:height]; 25 } 26 27
@end   (2)在登录调控器中装置开关样式 1 // 2 //
HVWLoginViewController.m 3 // HelloLottery 4 // 5 // Created by
hellovoidworld on 15/54%. 6 // Copyright (c) 二〇一五年 hellovoidworld. All
rights reserved. 7 // 8 9 #import “HVWLoginViewController.h” 10
#import “UIImage+Extend.h” 11 12 @interface HVWLoginViewController ()
13 14 /** 登录按键 */ 15 @property (weak, nonatomic) IBOutlet
UIButton *loginButton; 16 17 @end 18 19 @implementation
HVWLoginViewController 20 21 – (void)viewDidLoad { 22 [super
viewDidLoad]; 23 // Do any additional setup after loading the view. 24
25 UIImage *normal = [UIImage resizableImage:@”RedButton”]; 26
UIImage *highlighted = [UIImage resizableImage:@”RedButtonPressed”];
27 28 [self.loginButton setBackgroundImage:normal
forState:UIControlStateNormal]; 29 [self.loginButton
setBackgroundImage:highlighted forState:UIControlStateHighlighted]; 30
} 31 32 – (void)didReceiveMemoryWarning { 33 [super
didReceiveMemoryWarning]; 34 // Dispose of any resources that can be
recreated. 35 } 36 37 38 @end    
美高梅手机版4858 1    
8.storyboard增添“设置”分界面(权且演示用) “作者的彩票” –> 右上角
“设置” 使用TableViewController 使用static cell展现内容
使用“customer”为cell的样式,自行拖入image、label和switch等
美高梅手机版4858 2    
9.装置按键宗旨,统一设置Navigation导航栏按键样式
美高梅手机版4858 3        
     

UI升级,iosui进级 A.须求1.优化品种设置2.自定义导航栏标题按键3.多版本管理4.iOS6和iOS7的适配5.装置开关背景6.装置值UIBarButtonItem样式…

 
大家都了解在IOS7在此之前,Xcode中自带的UITabBarController调控器的tabbar样子好丑,可不经常又想行使UITabBarController来连忙切换分界面,那样就推抢到要自定义个中的tabbar。那么,怎么着技艺自定义贰个tabbar,具有与QQ只怕网易今日头条那样赏心悦指标分界面呢?

@class UIImage, UIFont, UIColor, UIImageView, UILabel;

兑现思路:首先进行全屏截图,在开始展览局部截图,就这么简单;

美高梅手机版4858 4

typedef NS_ENUM(NSInteger, UIButtonType) {

1.全屏截图:

 

//以枚举的貌似表示—button的分界面情势

– (UIImage *)getSnapshotImage { 
UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.view.frame),
CGRectGetHeight(self.view.frame)), NO, 1);   

 

UIButtonTypeCustom = 0,                        // no button type

 [self.view drawViewHierarchyInRect:CGRectMake(0, 0,
CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))
afterScreenUpdates:NO];    

 
 如上海体育场所中,大家的对象是自定义tabbar做成图中下方的表率,那样点击下方,以高速切换分界面。

UIButtonTypeSystem NS_ENUM_AVAILABLE_IOS(7_0),  // standard system
button

UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();   
UIGraphicsEndImageContext();   

 

UIButtonTypeDetailDisclosure,

 return snapshot;

 

UIButtonTypeInfoLight,

}

 

UIButtonTypeInfoDark,

2.局地截图

   思路:1.概念贰个GXViewController类承袭自UITabBarController

UIButtonTypeContactAdd,

+ (UIImage *)ct_imageFromImage:(UIImage *)image
inRect:(CGRect)rect{  

 

UIButtonTypePlain API_AVAILABLE(tvos(11.0)) __IOS_PROHIBITED
__WATCHOS_PROHIBITED, // standard system button without the blurred
background view

  //把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)

    2.将原来的tabbar掩盖,自定义一个控件覆盖在上头

UIButtonTypeRoundedRect = UIButtonTypeSystem  // Deprecated, use
UIButtonTypeSystem instead

//    CGFloat scale = [UIScreen mainScreen].scale;

 

};

//    CGFloat x=
rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;// 
  CGRect dianRect = CGRectMake(x, y, w, h);       

    3.在控件内扩展能够点击的开关,调解控件和开关的有血有肉细节,以高达上海体育场所中的效果。

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIButton : UIControl+
(instancetype)buttonWithType:(UIButtonType)buttonType;//创建button

 //截取部分图片并生成新图片   

 

@property(nonatomic)          UIEdgeInsets contentEdgeInsets
UI_APPEARANCE_SELECTOTucson; // default is UIEdgeInsetsZero. On tvOS 10 or
later, default is nonzero except for custom
buttons.调治button全体之中区域的岗位和尺寸

 CGImageRef sourceImageRef = [image CGImage];  

 

@property(nonatomic)          UIEdgeInsets titleEdgeInsets;             
  // default is UIEdgeInsetsZero–调度button文字区域的义务和尺寸

  CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef,
rect);    UIImage *newImage = [UIImage imageWithCGImage:newImageRef
scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]; 
  

 

@property(nonatomic)          BOOL       
reversesTitleShadowWhenHighlighted; // default is NO. if YES, shadow
reverses to shift between engrave and emboss appearance

return newImage;

现实代码如下:

@property(nonatomic)          UIEdgeInsets imageEdgeInsets;             
  // default is UIEdgeInsetsZero—–调治button图片区域的地方和尺寸

}

 

@property(nonatomic)          BOOL        adjustsImageWhenHighlighted; 
  // default is YES. if YES, image is drawn darker when
highlighted(pressed)

3.拖动视图 

在GXViewController的.m文件中

@property(nonatomic)          BOOL        adjustsImageWhenDisabled;     
// default is YES. if YES, image is drawn lighter when disabled

UIPanGestureRecognizer * panGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self                 
                                                                   
action:@selector(doHandlePanAction:)]; 

 

@property(nonatomic)          BOOL        showsTouchWhenHighlighted
__TVOS_PROHIBITED;      // default is NO. if YES, show a simple
feedback (currently a glow) while highlighted

 [_areaIamgeView addGestureRecognizer:panGestureRecognizer];

复制代码

@property(null_resettable, nonatomic,strong)  UIColor    *tintColor
NS_AVAILABLE_IOS(5_0); // The tintColor is inherited through the
superview hierarchy. See UIView for more information.

-(void)doHandlePanAction:(UIPanGestureRecognizer *)paramSender{    

 1 #import “GXViewController.h”

@property(nonatomic,readonly) UIButtonType buttonType;

CGPoint point = [paramSender translationInView:self.view];   
paramSender.view.center = CGPointMake(paramSender.view.center.x +
point.x, paramSender.view.center.y + point.y);    [paramSender
setTranslation:CGPointMake(0, 0) inView:self.view];

 2 

// you can set the image, title color, title shadow color, and
background image to use for each state. you can specify data

}

 3 #import “GXCustomButton.h”

// for a combined state by using the flags added together. in general,
you should specify a value for the normal state to be used

直白上代码,能够一直粘贴复制运转:(不要在意细节)

 4 

// by other states which don’t have a custom value set

#import@interface ViewController : UIViewController

 5 @interface GXViewController ()

– (void)setTitle:(nullable NSString *)title
forState:(UIControlState)state;                    // default is nil.
title is assumed to be single line

@end

 6 {

– (void)setTitleColor:(nullable UIColor *)color
forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default if
nil. use opaque white

#import “ViewController.h”

 7     

– (void)setTitleShadowColor:(nullable UIColor *)color
forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default is
nil. use 50% black

@interface ViewController ()

 8     UIImageView *_tabBarView; //自定义的掩饰原先的tarbar的控件

– (void)setImage:(nullable UIImage *)image
forState:(UIControlState)state;                      // default is nil.
should be same size if different for different states

@property(nonatomic,strong)UIImageView *backImageView;

 9     

– (void)setBackgroundImage:(nullable UIImage *)image
forState:(UIControlState)state UI_APPEARANCE_SELECTOR; // default is
nil

@property(nonatomic,strong)UIImageView *areaIamgeView;

10     GXCustomButton *_previousBtn; //记录前一遍当选的按键

– (void)setAttributedTitle:(nullable NSAttributedString *)title
forState:(UIControlState)state NS_AVAILABLE_IOS(6_0); // default is
nil. title is assumed to be single line

@end

11     

– (nullable NSString *)titleForState:(UIControlState)state;         
// these getters only take a single state value

@implementation ViewController{

12 }

– (nullable UIColor *)titleColorForState:(UIControlState)state;

UIView *_backView;

13 

– (nullable UIColor *)titleShadowColorForState:(UIControlState)state;

CGRect _rect;

14 @end

– (nullable UIImage *)imageForState:(UIControlState)state;

}

15 

– (nullable UIImage *)backgroundImageForState:(UIControlState)state;

– (void)viewDidLoad {

16 

– (nullable NSAttributedString
*)attributedTitleForState:(UIControlState)state
NS_AVAILABLE_IOS(6_0);

[super viewDidLoad];

17 

// these are the values that will be used for the current state. you can
also use these for overrides. a heuristic will be used to

// Do any additional setup after loading the view, typically from a nib.

18 @implementation GXViewController

// determine what image to choose based on the explict states set. For
example, the ‘normal’ state value will be used for all states

[self backImageView];

19 

// that don’t have their own image defined.

[self areaIamgeView];

20 – (void)viewDidLoad

@property(nullable, nonatomic,readonly,strong) NSString *currentTitle; 
          // normal/highlighted/selected/disabled. can return nil

UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];

21 {

@property(nonatomic,readonly,strong) UIColor  *currentTitleColor;     
  // normal/highlighted/selected/disabled. always returns non-nil.
default is white(1,1)

button.frame=CGRectMake(0, self.view.frame.size.height-44,
self.view.frame.size.width, 44);

22     

@property(nullable, nonatomic,readonly,strong) UIColor 
*currentTitleShadowColor;  // normal/highlighted/selected/disabled.

button.backgroundColor=[UIColor blueColor];

23     [super viewDidLoad];

@property(nullable, nonatomic,readonly,strong) UIImage  *currentImage; 
          // normal/highlighted/selected/disabled. can return nil

[button addTarget:self action:@selector(buttonClick)
forControlEvents:UIControlEventTouchUpInside];

24     

@property(nullable, nonatomic,readonly,strong) UIImage 
*currentBackgroundImage;  // normal/highlighted/selected/disabled. can
return nil

[self.view addSubview:button];

25     

@property(nullable, nonatomic,readonly,strong) NSAttributedString
*currentAttributedTitle NS_AVAILABLE_IOS(6_0);  //
normal/highlighted/selected/disabled. can return nil

}

26     self.tabBar.hidden = YES; //遮盖原先的tabBar

// return title and image views. will always create them if necessary.
always returns nil for system buttons

//这里对视图进行拖动

27     CGFloat tabBarViewY = self.view.frame.size.height – 49;

@property(nullable, nonatomic,readonly,strong) UILabel    *titleLabel
NS_AVAILABLE_IOS(3_0);

-(void)doHandlePanAction:(UIPanGestureRecognizer *)paramSender{

28     

@property(nullable, nonatomic,readonly,strong) UIImageView *imageView 
NS_AVAILABLE_IOS(3_0);

CGPoint point = [paramSender translationInView:self.view];

29     _tabBarView = [[UIImageView alloc]
initWithFrame:CGRectMake(0, tabBarViewY, 320, 49)];

/ these return the rectangle for the background (assumes bounds), the
content (image + title) and for the image and title separately. the
content rect is calculated based

NSLog(@”X:%f;Y:%f”,point.x,point.y);

30     _tabBarView.userInteractionEnabled = YES;
//这一步必须要设置为YES,不然不可能和用户交互

// on the title and image size and padding and then adjusted based on
the control content alignment. there are no draw methods since the
contents

paramSender.view.center = CGPointMake(paramSender.view.center.x +
point.x, paramSender.view.center.y + point.y);

31     _tabBarView.image = [UIImage imageNamed:@”背景图片”];

// are rendered in separate subviews (UIImageView, UILabel)

[paramSender setTranslation:CGPointMake(0, 0) inView:self.view];

32     

– (CGRect)backgroundRectForBounds:(CGRect)bounds;

}

33     [self.view addSubview:_tabBarView];

– (CGRect)contentRectForBounds:(CGRect)bounds;//
用来测算按键全部内容区域的高低和地方

-(void)jietu{

34     

– (CGRect)titleRectForContentRect:(CGRect)contentRect;//
用来总结开关文字区域的尺寸和位置

UIImage *image=[self getSnapshotImage];

35     // 下边包车型大巴不二诀借使调用自定义的变化开关的形式

– (CGRect)imageRectForContentRect:(CGRect)contentRect;//
用来测算开关图片区域的尺寸和地点

_backView=[[UIView alloc]initWithFrame:self.view.frame];

36     [self
creatButtonWithNormalName:@”图片1″andSelectName:@”图片2″andTitle:@”消息”andIndex:0];

@end

_backView.backgroundColor=[UIColor whiteColor];

37     [self
creatButtonWithNormalName:@”图片3″andSelectName:@”图片4″andTitle:@”联系人”andIndex:1];

@interface UIButton(UIButtonDeprecated)

[self.view addSubview:_backView];

38     [self
creatButtonWithNormalName:@”图片5″andSelectName:@”图片6″andTitle:@”动态”andIndex:2];

@property(nonatomic,strong) UIFont *font NS_DEPRECATED_IOS(2_0,
3_0) __TVOS_PROHIBITED;

UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];

39     [self
creatButtonWithNormalName:@”图片7″andSelectName:@”图片8″andTitle:@”设置”andIndex:3];

@property(nonatomic) NSLineBreakMode lineBreakMode
NS_DEPRECATED_IOS(2_0, 3_0) __TVOS_PROHIBITED;

button.frame=CGRectMake(0, self.view.frame.size.height-44,
self.view.frame.size.width, 44);

40     

@property(nonatomic) CGSize titleShadowOffset NS_DEPRECATED_IOS(2_0,
3_0) __TVOS_PROHIBITED;

button.backgroundColor=[UIColor blueColor];

41     GXCustomButton *btn = _tabBarView.subviews[0];

@end#if TARGET_OS_IOS

[button addTarget:self action:@selector(cancelButtonClick)
forControlEvents:UIControlEventTouchUpInside];

42     

@interface UIButton (SpringLoading)

[_backView addSubview:button];

43     [self changeViewController:btn];
//自定义的控件中的按键被点击了调用的措施,暗中同意步向分界面就当选第七个开关

@end

UIImageView *checkImageView=[[UIImageView alloc]init];

44     

#endif

checkImageView.center=_backView.center;

45 }

NS_ASSUME_NONNULL_END

checkImageView.bounds=CGRectMake(0, 0, 200, 200);

46 

留神:暗中认可情况下,Cocoa Touch
框架中的UIButton只帮助左图右文的布局方式,并且还不能够直接设置图像和文字间距。

checkImageView.contentMode=UIViewContentModeScaleAspectFit;

47 #pragma mark 创建多个开关

只是在实际开垦中,我们会遇到需求–上海体育场地片下文字;右图左文;上文下图的动静。

[_backView addSubview:checkImageView];

48 – (void)creatButtonWithNormalName:(NSString *)normal
andSelectName:(NSString *)selected andTitle:(NSString *)title
andIndex:(int)index

本着这种场所,大家的平时思路就是开创UIButton的子类或然项目

UIImage *newImage=[ViewController ct_imageFromImage:image
inRect:_美高梅手机版4858 ,rect];

49 {

UIButton的类别

#import<UIKit/UIKit.h>

//系统暗中认可的布局是内容完全居中,图片在左,文字在右,图片和文字间距为 0。

typedef NS_ENUM(NSInteger,ZBButtonLayoutStyle) {

ZBButtonLayoutTitleLeft,

ZBButtonLayoutTitleRight,

ZBButtonLayoutTitleTop,

ZBButtonLayoutTitleBottom,

};

@interface UIButton (TitleAndImageLayout)

– (void)zb_setLayoutStyle:(ZBButtonLayoutStyle)style
spacing:(CGFloat)spacing;

@end

#import “UIButton+TitleAndImageLayout.h”

@implementation UIButton (TitleAndImageLayout)

– (void)zb_setLayoutStyle:(ZBButtonLayoutStyle)style
spacing:(CGFloat)spacing{

[self layoutIfNeeded];//为了获得最新的 imageView 和 titleLabel 的
frame,强制更新

CGRect titleFrame = self.titleLabel.frame;

CGRect imageFrame = self.imageView.frame;

switch (style) {

//  UIEdgeInsets 类型有四个分子变量
top、left、bottom、right,分别代表上左下右五个样子的偏移量,正值代表往内缩进,也正是往按键主题靠拢,负值代表往外扩展,正是往开关边缘贴近。

case ZBButtonLayoutTitleLeft:

{

// 图片右移

self.imageEdgeInsets = UIEdgeInsetsMake(0,

titleFrame.size.width + spacing,

0,

-(titleFrame.size.width + spacing));

// 文字左移

self.titleEdgeInsets = UIEdgeInsetsMake(0,

-(titleFrame.origin.x – imageFrame.origin.x),

0,

titleFrame.origin.x – imageFrame.origin.x);

}

break;

case ZBButtonLayoutTitleRight:

{

// 总括暗中认可的图样文字间距

CGFloat originalSpacing = titleFrame.origin.x – (imageFrame.origin.x +
imageFrame.size.width);

// 调治文字的职责

self.titleEdgeInsets = UIEdgeInsetsMake(0,

-(originalSpacing – spacing),

0,

(originalSpacing – spacing));

}

break;

case ZBButtonLayoutTitleTop:

{

// 图片下移,右移

self.imageEdgeInsets = UIEdgeInsetsMake(titleFrame.size.height +
spacing,

0,

0,

-(titleFrame.size.width));

// 文字上移,左移

self.titleEdgeInsets = UIEdgeInsetsMake(0,

-(imageFrame.size.width),

imageFrame.size.height + spacing,

0);

}

break;

case ZBButtonLayoutTitleBottom:

{

// 图片上移,右移

self.imageEdgeInsets = UIEdgeInsetsMake(0,

0,

titleFrame.size.height + spacing,

-(titleFrame.size.width));

// 文字下移,左移

self.titleEdgeInsets = UIEdgeInsetsMake(imageFrame.size.height +
spacing,

-(imageFrame.size.width),

0,

0);

}

break;

default:

break;

}

}

@end

checkImageView.image=newImage;

50     /*

选用办法

//button的深浅会自动获得图片的深浅,字体大小暗许17

UIButton* left = [UIButton buttonWithType:UIButtonTypeCustom];

left.backgroundColor = [UIColor yellowColor];

[self.view addSubview:left];

left.frame = CGRectMake(50, 80, 50, 80);

[left setImage:[UIImage imageNamed:@”icon_交易格局@2x”]
forState:UIControlStateNormal];

[left setTitle:@”左” forState:UIControlStateNormal];

left.titleLabel.font = [UIFont systemFontOfSize:36];

[left setTitleColor:[UIColor redColor]
forState:UIControlStateNormal];

[left zb_setLayoutStyle:ZBButtonLayoutTitleLeft spacing:2];

}

51    
 GXCustomButton是自定义的三个三翻五次自UIButton的类,自定义该类的目标是因为系统自带的Button能够设置image和title属性,但是暗中认可的image是在title的左臂,若想想上面图片中那么,将image放在title的方面,就须求自定义Button,设置某事物。(具体GXCustomButton设置了如何,放在下边讲)

创建UIButton的子类

#import<UIKit/UIKit.h>

typedef NS_ENUM(NSInteger,ZBButtonLayoutStyle) {

ZBButtonLayoutTitleLeft,

ZBButtonLayoutTitleRight,

ZBButtonLayoutTitleTop,

ZBButtonLayoutTitleBottom,

};

@interface UILayoutButton : UIButton

@property (assign,nonatomic)IBInspectable CGSize imageSize;//图片大小

@property (nonatomic,assign)CGFloat
titleAndImageSpace;//文字和图表间的离开

@property (assign, nonatomic) ZBButtonLayoutStyle layoutStyle;   
///< 图片和文字的相对地方

@end


#import “UILayoutButton.h”

@implementation UILayoutButton

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during
animation.

– (void)drawRect:(CGRect)rect {

// Drawing code

}

*/

– (void)setLayoutStyle:(ZBButtonLayoutStyle)layoutStyle{

_layoutStyle = layoutStyle;

if (layoutStyle!= ZBButtonLayoutTitleRight&&layoutStyle!=
ZBButtonLayoutTitleLeft) {

self.titleLabel.textAlignment = NSTextAlignmentCenter;

}

}

#pragma mark—重写父类方法,退换title和image的坐标

– (CGRect)imageRectForContentRect:(CGRect)contentRect{

if (self.layoutStyle == ZBButtonLayoutTitleLeft) {

CGFloat x = contentRect.size.width – self.titleAndImageSpace –
self.imageSize.width ;

CGFloat y =  contentRect.size.height –  self.imageSize.height;

y = y/2;

CGRect rect =
CGRectMake(x,y,self.imageSize.width,self.imageSize.height);

return rect;

} else if (self.layoutStyle == ZBButtonLayoutTitleBottom) {

CGFloat x =  contentRect.size.width –  self.imageSize.width;

CGFloat  y=  0  ;

x = x / 2;

CGRect rect =
CGRectMake(x,y,self.imageSize.width,self.imageSize.height);

return rect;

}else if (self.layoutStyle == ZBButtonLayoutTitleTop){

CGFloat x =  contentRect.size.width –  self.imageSize.width;

CGFloat  y= 
contentRect.size.height-self.titleAndImageSpace-self.imageSize.height  ;

x = x / 2;

CGRect rect =
CGRectMake(x,y,self.imageSize.width,self.imageSize.height);

return rect;

}

else {

return [super imageRectForContentRect:contentRect];

}

}

– (CGRect)titleRectForContentRect:(CGRect)contentRect {

if (self.layoutStyle == ZBButtonLayoutTitleLeft) {

return CGRectMake(0, 0, contentRect.size.width – self.titleAndImageSpace

  • self.imageSize.width , contentRect.size.height);

} else if (self.layoutStyle == ZBButtonLayoutTitleBottom) {

return CGRectMake(0,  self.titleAndImageSpace + self.imageSize.height ,
contentRect.size.width , contentRect.size.height –
self.titleAndImageSpace – self.imageSize.height );

}

else if (self.layoutStyle == ZBButtonLayoutTitleTop){

return CGRectMake((contentRect.size.width- self.imageSize.width)/2.0 , 
0 , contentRect.size.width , contentRect.size.height –
self.titleAndImageSpace – self.imageSize.height );

}

else {

return [super titleRectForContentRect:contentRect];

}

}

@end

-(void)buttonClick{

52      */

选择格局:

UILayoutButton *left = [UILayoutButton
buttonWithType:UIButtonTypeCustom];

left.backgroundColor = [UIColor redColor];

left.titleLabel.backgroundColor = [UIColor grayColor];

left.imageView.backgroundColor = [UIColor purpleColor];

left.frame = CGRectMake(50, 160, 110, 30);

[left setTitle:@”标题在左” forState:UIControlStateNormal];

left.imageSize = CGSizeMake(20, 20);//设置图片大小

left.layoutStyle = ZBButtonLayoutTitleLeft;//布局风格

[left setImage:[UIImage imageNamed:@”check_icon”]
forState:UIControlStateNormal];

[self.view addSubview:left];

NSLog(@”%f,%f,%f,%f”,self.areaIamgeView.frame.origin.x,self.areaIamgeView.frame.origin.y,self.areaIamgeView.frame.size.width,self.areaIamgeView.frame.size.height);

53     

总结:

上述措施都能兑现再一次布局UIButton的子控件的功用,各有利害:

诸君,能够把您的见识留在下方斟酌区。如有不足,也请指教,笔者这里就抱砖引玉了。

_rect=self.areaIamgeView.frame;

54     GXCustomButton *button = [GXCustomButton
buttonWithType:UIButtonTypeCustom];

_areaIamgeView.alpha=0;

55     button.tag = index;

[self performSelector:@selector(jietu) withObject:nil
afterDelay:0.05];

56     

}

57     

//获得全屏截图

58     CGFloat buttonW = _tabBarView.frame.size.width / 4;

– (UIImage *)getSnapshotImage {

59     CGFloat buttonH = _tabBarView.frame.size.height;

UIGraphicsBeginImageContextWithOptions(CGSizeMake(CGRectGetWidth(self.view.frame),
CGRectGetHeight(self.view.frame)), NO, 1);

60     button.frame = CGRectMake(80 *index, 0, buttonW, buttonH);

[self.view drawViewHierarchyInRect:CGRectMake(0, 0,
CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame))
afterScreenUpdates:NO];

61     

UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();

62     

UIGraphicsEndImageContext();

63     [button setImage:[UIImage imageNamed:normal]
forState:UIControlStateNormal];

return snapshot;

64     [button setImage:[UIImage imageNamed:selected]
forState:UIControlStateDisabled];

}

65     [button setTitle:title forState:UIControlStateNormal];

//截取部分图片

66     

+ (UIImage *)ct_imageFromImage:(UIImage *)image inRect:(CGRect)rect{

67     

//把像 素rect 转化为 点rect(如无转化则按原图像素取部分图片)

68     [button addTarget:self action:@selector(changeViewController:)
forControlEvents:UIControlEventTouchDown];

//    CGFloat scale = [UIScreen mainScreen].scale;

69     

//    CGFloat x=
rect.origin.x*scale,y=rect.origin.y*scale,w=rect.size.width*scale,h=rect.size.height*scale;

70     button.imageView.contentMode = UIViewContentModeCenter; //
让图片在开关内居中

//    CGRect dianRect = CGRectMake(x, y, w, h);

71     button.titleLabel.textAlignment = NSTextAlignmentCenter; //
让题目在按键内居中

//截取部分图片并生成新图片

72     button.font = [UIFont systemFontOfSize:12]; //
设置题指标字体大小

CGImageRef sourceImageRef = [image CGImage];

73     

CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef,
rect);

74     [_tabBarView addSubview:button];

UIImage *newImage = [UIImage imageWithCGImage:newImageRef
scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];

75     

return newImage;

76 }

}

77 

-(void)cancelButtonClick{

78 

self.areaIamgeView.alpha=1;

79 

[_backView removeFromSuperview];

80 #pragma mark 按键被点击时调用

}

81 – (void)changeViewController:(GXCustomButton *)sender

-(UIImageView *)backImageView{

82 {

if (!_backImageView) {

83     self.selectedIndex = sender.tag; //切换差别调控器的分界面

_backImageView=[[UIImageView alloc]init];

84     

_backImageView.frame=self.view.frame;

85     sender.enabled = NO;

_backImageView.image=[UIImage imageNamed:@”1.jpg”];

86     

_backImageView.contentMode=UIViewContentModeScaleAspectFit;

87     if (_previousBtn != sender) {

[self.view addSubview:_backImageView];

88         

}

89         _previousBtn.enabled = YES;

return _backImageView;

90         

}

91     }

-(UIImageView *)areaIamgeView{

92     

if (!_areaIamgeView) {

93     _previousBtn = sender;

_areaIamgeView=[[UIImageView alloc]init];

94     

_areaIamgeView.center=self.view.center;

95 }

_areaIamgeView.bounds=CGRectMake(0, 0, 100, 100);

96 

_areaIamgeView.backgroundColor=[UIColor whiteColor];

97 @end

_areaIamgeView.alpha=0.8;

 

_areaIamgeView.userInteractionEnabled=YES;

 

UIPanGestureRecognizer * panGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self

自定义的GXCustomButton按键.m中的代码如下:

action:@selector(doHandlePanAction:)];

 

[_areaIamgeView addGestureRecognizer:panGestureRecognizer];

 

[self.view addSubview:_areaIamgeView];

 1 #import “GXCustomButton.h”

}

 2 

return _areaIamgeView;

 3 @implementation GXCustomButton

}

 4 

– (void)didReceiveMemoryWarning {

 5 #pragma mark 设置Button内部的image的范围

[super didReceiveMemoryWarning];

 6 – (CGRect)imageRectForContentRect:(CGRect)contentRect

// Dispose of any resources that can be recreated.

 7 {

}

 8     CGFloat imageW = contentRect.size.width;

@end

 9     CGFloat imageH = contentRect.size.height * 0.6;

10     

11     return CGRectMake(0, 0, imageW, imageH);

12 }

13 

14 #pragma mark 设置Button内部的title的范围

15 – (CGRect)titleRectForContentRect:(CGRect)contentRect

16 {

17     CGFloat titleY = contentRect.size.height *0.6;

18     CGFloat titleW = contentRect.size.width;

19     CGFloat titleH = contentRect.size.height – titleY;

20     

21     return CGRectMake(0, titleY, titleW, titleH);

22 }

23 

24 @end

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有