iOS 自定义button

  UIButton默认的布局是左侧image,右侧title,如果想要改变image与title的frame,直接设置是不会有效果的。可以通过titleEdgeInsets、imageEdgeInsets分别修改image与title的位置。也可以通过继承UIButton,重写以下方法来自定义frame

//image的frame
- (CGRect)imageRectForContentRect:(CGRect)contentRect;

//title的frame
- (CGRect)titleRectForContentRect:(CGRect)contentRect;

  示例代码如下:

  

- (CGRect)titleRectForContentRect:(CGRect)contentRect
{
    CGRect imageF;
    CGFloat w;
    CGFloat h;
    CGFloat x;
    CGFloat y;
    
     imageF = self.imageView.frame;
     w = contentRect.size.width - imageF.size.width;
     h = 20;
     x = 0;
     y = 10;
        
        
        
    
    return CGRectMake(x, y, w, h);
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect
{
    CGFloat w;
    CGFloat h;
    CGFloat x;
    CGFloat y;
    w = kImageWH;
    h = kImageWH;
    x = contentRect.size.width - w;
    y = 10;
      
            
    return CGRectMake(x, y, w, h);
}

  

转载于:https://www.cnblogs.com/pretty-guy/p/4897775.html

猜你喜欢

转载自blog.csdn.net/weixin_34320159/article/details/93438655