美文网首页iOS表格绘制
iOS开发之调整UIButton 图片(imageView)与文

iOS开发之调整UIButton 图片(imageView)与文

作者: 朱晓晓的技术博客 | 来源:发表于2019-01-23 16:10 被阅读8次

    UIButton可以同时设置Title和Image,UIButton有两个属性:titleEdgeInsets(top,left,bottom,right)和imageEdgeInsets(top,left,bottom,right),通过设置这两个,就可以实现所有需要的Button的样式
    UIButton 的 默认状态下imageEdgeInsets = UIEdgeInsetsMake(0,0,0,0);titleEdgeInsets = UIEdgeInsetsMake(0,0,0,0); 图片在左文字在右,而且整体水平和垂直居中 。比如下面这个图文按钮:

    image

    为了最美观一点,可以设置图标与文字间距 。如下图:

    image
    //button标题的偏移量,这个偏移量是相对于图片的
    _rightBut.titleEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
    
    

    设置图片在右文字在左:

    image
    // button标题的偏移量 
    self.locationBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -self.locationBtn.imageView.bounds.size.width+2, 0, self.locationBtn.imageView.bounds.size.width);
     // button图片的偏移量
    self.locationBtn.imageEdgeInsets = UIEdgeInsetsMake(0, self.locationBtn.titleLabel.bounds.size.width, 0, -self.locationBtn.titleLabel.bounds.size.width);
    
    

    设置图片在上,文字在下:

    image
    // button标题的偏移量
    self.eightButton.titleEdgeInsets = UIEdgeInsetsMake(self.eightButton.imageView.frame.size.height+5, -self.eightButton.imageView.bounds.size.width, 0,0);
    // button图片的偏移量
    self.eightButton.imageEdgeInsets = UIEdgeInsetsMake(0, self.eightButton.titleLabel.frame.size.width/2, self.eightButton.titleLabel.frame.size.height+5, -self.eightButton.titleLabel.frame.size.width/2);
    
    

    设置图片左对齐:

    image
    //button文字的偏移量
     _Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  -(_Choosebutton1.imageView.frame.origin.x+_Choosebutton1.imageView.frame.size.width), 0, 0);
    //button图片的偏移量
    _Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, -(_Choosebutton1.imageView.frame.origin.x ), 0, _Choosebutton1.imageView.frame.origin.x);
    
    

    设置文字右对齐:

    image
    //button文字的偏移量
     _Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  0, 0, -(_Choosebutton1.frame.size.width - _Choosebutton1.titleLabel.frame.origin.x -_Choosebutton1.titleLabel.frame.size.width));
    //button图片的偏移量
    _Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, -(_Choosebutton1.imageView.frame.origin.x ), 0, _Choosebutton1.imageView.frame.origin.x);
    
    

    设置文字左对齐,图片右对齐:

    image
    _Choosebutton1.titleEdgeInsets = UIEdgeInsetsMake(0,  -(_Choosebutton1.titleLabel.frame.origin.x+20), 0, 0);
    
    _Choosebutton1.imageEdgeInsets = UIEdgeInsetsMake(0, (_Choosebutton1.frame.size.width - _Choosebutton1.imageView.frame.origin.x - _Choosebutton1.imageView.frame.size.width), 0, -(_Choosebutton1.frame.size.width - _Choosebutton1.imageView.frame.origin.x - _Choosebutton1.imageView.frame.size.width));
    

    作者:emily_sky
    链接:https://www.jianshu.com/p/d23a8234729c

    相关文章

      网友评论

        本文标题:iOS开发之调整UIButton 图片(imageView)与文

        本文链接:https://www.haomeiwen.com/subject/omfsjqtx.html