Button的基本使用
既能顯示文字,又能顯示圖片
-
UIButton的狀態:
-
normal
(普通狀態): UIControlStateNormal -
highlighted
(高亮狀態):UIControlStateHighlighted -
disabled
(失效狀態,不可用狀態):UIControlStateDisabled
-
-
UIButton的文字和圖片的設置
//設置按鈕的文字 - (void)setTitle:(NSString *)title forState:(UIControlState)state; //設置按鈕的文字顏色 - (void)setTitleColor:(UIColor *)color forState:(UIControlState)state; //設置按鈕內部的小圖片 - (void)setImage:(UIImage *)image forState:(UIControlState)state; //設置按鈕的背景圖片 - (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state; //設置按鈕的文字字體(需要拿到按鈕內部的label來設置) btn.titleLabel.font = [UIFont systemFontOfSize:13];
-
獲得Button的一些屬性
//獲得按鈕的文字 - (NSString *)titleForState:(UIControlState)state; //獲得按鈕的文字顏色 - (UIColor *)titleColorForState:(UIControlState)state; //獲得按鈕內部的小圖片 - (UIImage *)imageForState:(UIControlState)state; //獲得按鈕的背景圖片 - (UIImage *)backgroundImageForState:(UIControlState)state;
Button的常見用法
- button的內部有兩個子控件一個是imageView一個是titleLabel
- 因為有titleLabel屬性所以button可以不用設置寬高,設置位置即可
- button設置文字、文字顏色、標題、背景圖片、圖片等都需要說明是在什么狀態下的。但是可以設置titleLabel的文字大小,因為這樣不管是什么狀態下都是該字體大小:
button.titleLabel.font = [UiFont systemFontOfSize:16];
- 可以設置button的contentEdgeInsets屬性,表示上下左右有多少尺寸不作為顯示內容的地方:
button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
表示button的上下左右各有20的尺寸不顯示 - 在聊天布局的demo中,文字的titleLabel的大小正好填充了button的大小,但是由于button的背景圖片上下左右的各有20的透明像素,所以在設置的時候背景圖片被拉伸了。設置button的contentEdgeInsets的上下左右各有20的尺寸那么正好titleLabel的顯示的內容在其中,先是button根據titleLabel的大小有了此存,然后在titleLabel的基礎上再加上2 * 20,這個就是button的高度
- 自定義cell實現圖片在上面文字在下面的效果
- 第一種:實現
layoutSubviews
方法在里面布局 - 第二種: 在下面的方法中實現布局
//布局imageView的frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect{
}
//布局titleLabel的frame
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
}