有一個自定義UIButton,占了視圖的四分之一,我想要在按鈕標題上設置一張圖片,居中設置。
代碼:
CGRect imageFrame= CGRectMake(0, 0, 80, 80);
UIEdgeInsets imageInset = UIEdgeInsetsMake(0, 0, 30, 0);
UIEdgeInsets titleInset = UIEdgeInsetsMake(80, 0, 0, 0);
btnSideSettings = [UIButton buttonWithType:UIButtonTypeCustom];
btnSideSettings.frame = settingsFrame;
[btnSideSettings setImage:[UIImage imageNamed:@"btnSideSettings"] forState:UIControlStateNormal];
btnSideSettings.imageView.frame = imageFrame;
btnSideSettings.imageEdgeInsets = imageInset;
btnSideSettings.titleEdgeInsets = titleInset;
btnSideSettings.titleLabel.textAlignment = NSTextAlignmentCenter;
[btnSideSettings setTitle:@"Settings" forState:UIControlStateNormal];
結果:
如果注釋掉添加圖片,標題就會居中。
請明白人指點一下,謝謝。
可以換種方式來實現 。我這裡的方式是用UIImageView 來倒圓角實現 .注意這裡要導入一個庫
#import <QuartzCore/QuartzCore.h>
UIImage *image=[UIImage imageNamed:@"btnSideSettings"];
UIImageView *imgView=[[UIImageView alloc] initWithImage:image];
/////給imgView進行圓形遮罩
imgView.layer.masksToBound=YES; ////required
imgView.layer.cornerRadius=imgView.frame.size.width/2; /////radiu is a half of imageview's width
如果在圖片上有點擊動作可用手勢來實現 。