zoukankan      html  css  js  c++  java
  • UIButton

    一、直接通过以下几个属性进行设置
    1 @property(nonatomic)      UIEdgeInsets titleEdgeInsets;                // default is UIEdgeInsetsZero
    2 @property(nonatomic)          UIEdgeInsets imageEdgeInsets;                // default is UIEdgeInsetsZero 
    如果同时设置图片和标题,会发现图片在左侧,标题在右侧,而一般情况下我们期望的是上图下字的布局。然后我们进入文档看到UIButton同提供了 以上两格字段来调整其内部布局:
    1》按上左下右设置图片的位置(很好,很完美)
    2》同样的按照上左下右设置标题label的位置,运行,我去label呢?怎么不见了???????
    注意:后来才知道,默认的img和title 的布局是相互影响的,除了以上两格字段,UIButton中还有以下字段
    1 @property(nonatomic)          UIEdgeInsets contentEdgeInsets UI_APPEARANCE_SELECTOR; // default is UIEdgeInsetsZero. On tvOS 10 or later, default is nonzero except for custom buttons.
    系统默认的把 img+title 当成一个矩形框放到button的正中间(想一想xib中的约束,这里可以认为title左侧的约束是相对于img的右侧来赋值的)
     
    title上下边界正常设置即可,对于左右的设置时需要注意,title左边界是以图片的右边为标准的如下图紫线
    所以如果想让标题以button的左侧为标准    就要把线向左移动 ( img的左边距 + imgSize.width )
     
    这一方法比较繁杂可以考虑第二种方法如下
    二、自定义一个Button继承自UIButton
    重写父类的方法
    1、第一种:
    // these return the rectangle for the background (assumes bounds), the content (image + title) and for the image and title separately. the content rect is calculated based
    // on the title and image size and padding and then adjusted based on the control content alignment. there are no draw methods since the contents
    // are rendered in separate subviews (UIImageView, UILabel)
    
    - (CGRect)backgroundRectForBounds:(CGRect)bounds;
    - (CGRect)contentRectForBounds:(CGRect)bounds;
    - (CGRect)titleRectForContentRect:(CGRect)contentRect;
    - (CGRect)imageRectForContentRect:(CGRect)contentRect;

      - (CGRect)titleRectForContentRect:方法返回的是标题的frame

      - (CGRect)imageRectForContentRect:返回的是imageview的frame

      - (CGRect)contentRectForBounds:返回的是imageview+title的矩形框的frame

      - (CGRect)backgroundRectForBounds:返回的是背景图片的frame

      当然这里frame都是相对于bounds来说的

    2、第二种:

    重写- (void)layoutSubviews方法,因为改变frame的时候会调用layoutSubviews方法进行子控件的布局

  • 相关阅读:
    hdu 1281 棋盘游戏(二分匹配)
    UVA 12545 Bits Equalizer
    算法之匈牙利算法
    I题 hdu 1234 开门人和关门人
    H题 hdu 2520 我是菜鸟,我怕谁
    G题 hdu 1466 计算直线的交点数
    F题 hdu 1431 素数回文
    E题hdu 1425 sort
    D题 hdu 1412 {A} + {B}
    有12个球,外形相同,其中一个小球的质量与其他11个不同,给一个天平,需要几次把这个小球找出来并且求出这个小球是比其他的轻还是重
  • 原文地址:https://www.cnblogs.com/zhhl/p/7542189.html
Copyright © 2011-2022 走看看