iPhone UIButton - image position

前端 未结 16 607
梦谈多话
梦谈多话 2020-12-04 06:18

I have a UIButton with text \"Explore the app\" and UIImage (>) In Interface Builder it looks like:

[ (>) Explore t         


        
16条回答
  •  悲哀的现实
    2020-12-04 07:05

    This solution works iOS 7 and above

    Just subclass UIButton

    @interface UIButton (Image)
    
    - (void)swapTextWithImage;
    
    @end
    
    @implementation UIButton (Image)
    
    - (void)swapTextWithImage {
       const CGFloat kDefaultPadding = 6.0f;
       CGSize buttonSize = [self.titleLabel.text sizeWithAttributes:@{
                                                                   NSFontAttributeName:self.titleLabel.font
                                                                   }];
    
       self.titleEdgeInsets = UIEdgeInsetsMake(0, -self.imageView.frame.size.width, 0, self.imageView.frame.size.width);
       self.imageEdgeInsets = UIEdgeInsetsMake(0, buttonSize.width + kDefaultPadding, 0, -buttonSize.width); 
    }
    
    @end
    

    Usage (Somewhere in your class):

    [self.myButton setTitle:@"Any text" forState:UIControlStateNormal];
    [self.myButton swapTextWithImage];
    

提交回复
热议问题