UITextField文字縮進等位置改變
只需創建一個UITextField
的子類,在子類中重寫幾個方法:
- (CGRect)borderRectForBounds:(CGRect)bounds; //邊界的位置
- (CGRect)textRectForBounds:(CGRect)bounds; //文字的位置
- (CGRect)placeholderRectForBounds:(CGRect)bounds; //占位文字的位置
- (CGRect)editingRectForBounds:(CGRect)bounds; //編輯時文字的位置
- (CGRect)clearButtonRectForBounds:(CGRect)bounds; //清除按鈕的位置
- (CGRect)leftViewRectForBounds:(CGRect)bounds; //左視圖的位置
- (CGRect)rightViewRectForBounds:(CGRect)bounds; //右視圖的位置
需要制定哪些位置就重寫哪些方法,其中參數bounds
是UITextField
的bounds
。
Tips:使用CGRectInset(CGRect rect, CGFloat dx, CGFloat dy)
可以快速得到左右都距離rect
dx
距離、上下都距離rect
dy
距離的CGRect
對象。
UIButton的titleLabel與imageView等視圖位置改變
- 方法一:與UITextField類似,創建子類,重寫方法:
- (CGRect)backgroundRectForBounds:(CGRect)bounds; //背景
- (CGRect)contentRectForBounds:(CGRect)bounds; //內容
- (CGRect)titleRectForContentRect:(CGRect)contentRect; //titleLabel
- (CGRect)imageRectForContentRect:(CGRect)contentRect; //imageView
-
方法二:使用
titleEdgeInsets
與imageEdgeInsets
兩個屬性:
</br>
titleEdgeInsets
與 imageEdgeInsets
都是UIEdgeInsets
類型的對象,可以使用UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right)
來得到,top
、left
、bottom
、right
分別指視圖到每一邊的距離。
但在 titleEdgeInsets
與 imageEdgeInsets
中,這四個值的含義又有點不同。
Tips:
titleEdgeInsets
與imageEdgeInsets
的四個值初始都是0。- 在設置完
title
和image
后,title
和image
的高度總是在button中居中的,它們的視圖大小也是不會變的。- 如果要得到
button
的titleLabel
的大小,簡單使用button.titleLabel.frame.size
你會發現得到的值是CGRectZero
,解決方法就是在獲取size
之前先調用sizeToFit
。
做個示例:
[button.titleLabel sizeToFit];
CGSize titleSize = button.titleLabel.frame.size;
button.titleEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, button.frame.size.height / 2.0 - titleSize.height / 2.0 + 10, button.frame.size.width, 1)];
line.backgroundColor = [UIColor blackColor];
[button addSubview:line];
這段代碼看上去是讓titleLabel
向下移動了10個單位,所以我在titleLabel
移動后的位置頂部畫了條線。
附上結果:
大家一定發現了實際上titleLabel
的位置并沒有向下移動了10個單位那么多。
原來,指定了titleEdgeInsets
的 top
為10,其實相當于button
的頂部縮短了10個單位,而titleLabel
高度要居中于button
,所以實際上titleLabel
只向下移動了5個單位,就像這樣:
再次嘗試將線上移5個單位,結果如下:
結論:若要 titleLabel
或 imageView
朝某個方向移動x
個單位,則需要把 titleEdgeInsets
或 imageEdgeInsets
中與方向對映的值改為2x
即可。
如果 title
和 image
都指定了,那么button
會將titleLabel
與 imageView
一起看為一個整體,而這個整體水平居中,例如:
了解了這個之后,就可以知道imageView
需要向右移動半個titleLabel
的寬度就可以水平居中,而titleLabel
需要向左移動半個imageView
的寬度就可以水平居中,再用上面提到的方法,就可以得到圖片在上,文字在下的UIButton
了。
注意:當title
和image
都要指定時,必須讓button
的寬高都大于兩者寬高之和,不然titleLabel
就會被縮小。