zoukankan      html  css  js  c++  java
  • UIButton设置图片和标题上下垂直分布的总结

    我们在使用UIButton的时候大多都是 图片 和 文字 水平分布的,当需要垂直分布的时候就需要去设置EdgeInsets:

    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使图片和文字水平居中显示
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(btn.imageView.frame.size.height ,-btn.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0.0, 0.0,0.0, -btn.titleLabel.bounds.size.width)];//图片距离右边框距离减少图片的宽度,其它不边

    但是当我用上面的方法设置过以后,改变标题文字多少的时候,图片的位置又变了,这种方法的通用性不行

    然后通过重写UIButton的-(void)layoutSubviews方法去实现,具体如下:

    -(void)layoutSubviews{
    
        [super layoutSubviews];
        
        CGFloat text_Height = 20.0;
        
        // Center image
        CGPoint center = self.imageView.center;
        center.x = self.frame.size.width/2.0;
        //center.y = self.imageView.frame.size.height/2.0;
        self.imageView.center = center;
        CGRect imgViewFrame = [self imageView].frame;
        imgViewFrame.origin.y = 10.0;
        imgViewFrame.size.height = self.frame.size.height - 25.0 - text_Height;
        imgViewFrame.size.width = self.frame.size.height - 25.0 - text_Height;
        self.imageView.frame = imgViewFrame;
        
        //Center text
        CGRect titleFrame = [self titleLabel].frame;
        titleFrame.origin.x = 0;
        titleFrame.origin.y = self.imageView.frame.origin.y + self.imageView.frame.size.height + 10.0;
        titleFrame.size.width = self.frame.size.width;
        titleFrame.size.height = text_Height;
        self.titleLabel.frame = titleFrame;
        
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }

    这种方法可以根据自己的需求去设置图片,文字的边距和大小,效果还是很好的

    另外如果你还是不满意的话,那就自定义吧,什么样的效果都可以用自定义去实现!

  • 相关阅读:
    ASP.NET MVC3 系列教程 部署你的WEB应用到IIS 6.0
    ASP.NET MVC3 系列教程 控制器 & 视图
    Windows 8 如何安装到Virtual Box虚拟机上(x86)
    工具脚本(网络编码)
    c库的rand/random随机数产生函数性能差?
    shell脚本模版
    linux的IO调度算法和回写机制
    thrift安装脚本
    通用高效的c++内存池(特定类型)
    [转] NoSQL生态系统
  • 原文地址:https://www.cnblogs.com/Rong-Shengcom/p/7122578.html
Copyright © 2011-2022 走看看