ios开发中UIButton设置标题和图片不能同时显示问题解决

 在之前的使用中一直存在按钮不能同时显示标题和图片的问题,只能创建类继承UIButton重新layoutSubViews方法实现。

今天在尝试了几次过后,当我改变Button的长度到一定范围时,发现标题和图片是能同时显示的,如图

然后尝试使用UIButton的属性titleEdgeInsets和imageEdgeInsets来设置发现也是可以的

代码:=====================================================

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame = CGRectMake(0, 100, 200,44);

    [button setBackgroundColor:[UIColor yellowColor]];

    [button setTitle:@"标题" forState:UIControlStateNormal];

    [button setImage:[UIImage imageNamed:@"wangwang_fill"] forState:UIControlStateNormal];

    

    //设置文字左对齐,设置button.titleLabel.textAlignment = NSTextAlignmentLeft无效

    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

    

    button.titleLabel.backgroundColor = [UIColor grayColor];

    button.imageView.backgroundColor = [UIColor redColor];

    [self.view addSubview:button];

//标题和图片换位显示

//button.titleEdgeInsets =UIEdgeInsetsMake(0,-button.imageView.bounds.size.width,0, +button.imageView.bounds.size.width);
//button.imageEdgeInsets = UIEdgeInsetsMake(0,button.titleLabel.bounds.size.width,0, - button.titleLabel.bounds.size.width);

    

    button.titleEdgeInsets = UIEdgeInsetsMake(0,-150,0,0);

    button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,150);

关于button.titleEdgeInsets和button.imageEdgeInsets的设置我发现如果设置imageEdgeInsets距离右150(将imageView压缩为长50),titleLabel好像就被推出去了,所以设置titleLabel距离左-150时,发现刚好贴合,如果需要文字与图片之间有空隙,只要设置为-140就行了。

但是当我把按钮长度设为100,   并且 button.titleEdgeInsets = UIEdgeInsetsMake(0,-50,0,0);   button.imageEdgeInsets = UIEdgeInsetsMake(0,0,0,50);时发现标题又不能显示了,设为-150时刚好能达到效果。所以对这两个属性的计算还是不太明白。

猜你喜欢

转载自blog.csdn.net/ljw2017/article/details/81666694