[英]How to center UIImageView within UIButton with its text?
我有一個UIButton
,即時消息添加這樣的圖像:
UIImageView *cardImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Visa.png"]];
cardImage.frame = CGRectMake(15, _cardButton.frame.size.height - 25 - 10, 25, 25);
cardImage.contentMode=UIViewContentModeScaleAspectFit;
[_cardButton addSubview:cardImage];
如何顯示以UIButton
的titleLable為中心的圖像?
//這樣嘗試
cardImage.frame = _cardButton.frame;
cardImage.center = _cardButton.center;
cardImage.contentMode=UIViewContentModeCenter;
試試這個可能對您有幫助
CGFloat flotspacing = 50; // the amount of spacing to appear between image and title
Btn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, flotspacing);
Btn.titleEdgeInsets = UIEdgeInsetsMake(0, flotspacing, 0, 0);
並使用.h和.m文件嘗試此代碼
UIButton + BtnPosition.h
@interface UIButton(ImageTitleCentering)
-(void) centerButtonPositionAndImageWithSpacing:(CGFloat)spacing;
@end
UIButton + BtnPosition.m
@implementation UIButton(ImageTitleCentering)
-(void) centerButtonPositionAndImageWithSpacing:(CGFloat)spacing {
self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);
}
@結束
現在調用以下函數
[button centerButtonPositionAndImageWithSpacing:10];
我使用此編碼在中心設置按鈕圖像和標題,這可能對您有所幫助。
謝謝...
與其添加imageview作為UIButton的子視圖,不如嘗試設置具有按鈕image屬性的圖像。
// the space between the image and text
CGFloat spacing = 6.0;
// lower the text and push it left so it appears centered
// below the image
CGSize imageSize = button.imageView.image.size;
button.titleEdgeInsets = UIEdgeInsetsMake(
0.0, - imageSize.width, - (imageSize.height + spacing), 0.0);
// raise the image and push it right so it appears centered
// above the text
CGSize titleSize = [button.titleLabel.text sizeWithAttributes:@{NSFontAttributeName: button.titleLabel.font}];
button.imageEdgeInsets = UIEdgeInsetsMake(
- (titleSize.height + spacing), 0.0, 0.0, - titleSize.width);
// increase the content height to avoid clipping
CGFloat edgeOffset = fabsf(titleSize.height - imageSize.height) / 2.0;
button.contentEdgeInsets = UIEdgeInsetsMake(edgeOffset, 0.0, edgeOffset, 0.0);
為什么要將UIImageView
作為子視圖添加到UIButton
。 UIButton
具有BackgroundImage
和Image
屬性以將圖像設置為按鈕。 將contentMode
屬性設置為center
以使圖像居中。
_cardButton.contentMode=UIViewContentModeCenter;
如果image
在UIButton
看起來太大,請減小image
的尺寸,或要求設計人員為圖像提供所需的Padding
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.