調整原生UIButton中title和image位置僅需調用此方法:
/** * 重新布局UIbutton * * @param button 所布局的UIbutton */ -(void)layoutBtnWithBtn:(UIButton *)button{ button.titleLabel.backgroundColor = button.backgroundColor; button.imageView.backgroundColor = button.backgroundColor; CGSize titleSize = button.titleLabel.bounds.size; CGSize imageSize = button.imageView.bounds.size; NSLog(@"titleSize :%@ \n imageSize:%@",NSStringFromCGSize(titleSize),NSStringFromCGSize(imageSize)); //文字左移 button.titleEdgeInsets = UIEdgeInsetsMake(0.0, -imageSize.width, 0.0, imageSize.width); //圖片右移 button.imageEdgeInsets = UIEdgeInsetsMake(0.0, titleSize.width, 0.0, -titleSize.width); }
在設置UIbutton title和image的情況下,系統會自動計算文本框和圖片的Frame,從而調整兩者位置.