Buttonの画像と文字の左右の位置を交換します

2550 ワード

Buttonの画像と文字の左右の位置を交換します


デフォルトではbuttonのimageとlabelが真ん中にくっついていますが、imageが右にある場合、labelが左にある場合はどうすればいいですか?
答えは次のとおりです.
self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
self.oneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);

なぜかというと、This property is used only for positioning the image during layout実はtitleEdgeInsets属性とimageEdgeInsets属性は、このbuttonを描くときにimageとlabelの位置を調整するために使用され、button自体の大きさに影響を与えない.それらはimageとbuttonが元の位置に比べてずれているだけで、何が元の位置なのでしょうか.edgeInsetが設定されていないときの位置です.
イメージが右にある場合、labelが左にある場合、イメージの左はbuttonの左に対してlabelWidthの距離を右に移動し、イメージの右はlabelの左に対してlabelWidthの距離を右に移動します.
だから、self.oneButton.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);なぜ負の値なのか.これはcontentInsetなので、オフセット量で、距離ではありません
同様に、labelの右側はbuttonの右側に対してimageWithの距離を左に移動し、labelの左はimageの右側に対してimageWithの距離を左に移動する
だからoneButton.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWith, 0, imageWith);
//  button, 
- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.currentImage == nil) return;

    CGFloat imageW = self.imageView.width;
    CGFloat labelW = self.titleLabel.width;

    self.imageEdgeInsets = UIEdgeInsetsMake(0, labelW, 0, -labelW);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, -imageW, 0, imageW);
}