- 1. 添加图片+文字/文字+图片 ,不分前后,图片默认在文字前边 加空格隔开
UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(, , , )];
button.backgroundColor =[UIColor grayColor];
//图片
[button setImage:[UIImage imageNamed:@"but"] forState:UIControlStateNormal]; //文字
[button setTitle:@" But文字" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.titleLabel.font =[UIFont boldSystemFontOfSize:]; [self.view addSubview:button];
- 2.设置文字图片 显示整体位置:居中、左、右; 单独设置文字的位置
- top : 为正数的时候,是往下偏移,为负数的时候往上偏移;
- left : 为正数的时候往右偏移,为负数的时候往左偏移;
- bottom : 为正数的时候往上偏移,为负数的时候往下偏移;
- right :为正数的时候往左偏移,为负数的时候往右偏移;
UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(, , , )];
button.backgroundColor =[UIColor grayColor];
//文字
[button setTitle:@"But文字" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.titleLabel.font =[UIFont boldSystemFontOfSize:];
//图片
[button setImage:[UIImage imageNamed:@"but"] forState:UIControlStateNormal]; /////////////修改///////////////////
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;//使图片和文字水平居中显示
/*
UIControlContentHorizontalAlignmentCente
UIControlContentHorizontalAlignmentLeft
UIControlContentHorizontalAlignmentRight
UIControlContentHorizontalAlignmentFill */
//文字 可以显示在 button 视图之外,但不接收点击事件响应
[button setTitleEdgeInsets:UIEdgeInsetsMake(button.imageView.frame.size.height ,button.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
/////////////////////////////////////// [self.view addSubview:button];
3.效果:
UIButton * button =[[UIButton alloc] initWithFrame:CGRectMake(, , , )];
button.backgroundColor =[UIColor grayColor];
//文字
[button setTitle:@"But文字" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.titleLabel.font =[UIFont boldSystemFontOfSize:];
//图片
[button setImage:[UIImage imageNamed:@"xia"] forState:UIControlStateNormal]; /////////////修改///////////////////
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
button.imageEdgeInsets = UIEdgeInsetsMake(,-, , ); //上左下右
//button.titleEdgeInsets = UIEdgeInsetsMake(0,300-50, 0, 0); // 设置文字的位置 上左下右
/////////////////////////////////////// [self.view addSubview:button];
4/ 但是图片尺寸大了 位置会错乱, 如有遇到的请评论指点