1. 程式人生 > >UIButton 設定image ,title和setBackgroundImage

UIButton 設定image ,title和setBackgroundImage

定製一個image 和title 有一定距離的UIButton

// 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
);

UIButton的setBackgroundImage 是設定背景圖片,而setImage則是設定一個挨著title的一個icon 或者image。
就是如果你設定的是backgroundImage 而不是image的話,那麼如果這個圖片過小的話這個圖片是會被拉伸的。