ios24--改变button的文字和图片

//
//  ViewController.m
//  09-UIButton内部子控件的调整
//
//  Created by xiaomage on 15/12/30.
//  Copyright © 2015年 小码哥. All rights reserved.
//

#import "ViewController.h"
#import "XMGButton.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 1.1 创建按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // 1.2 设置frame
    button.frame = CGRectMake(100, 100, 170, 70);//不设置fram看不见
    
    // 1.3 设置背景颜色
    button.backgroundColor = [UIColor purpleColor];
    
    // 1.4 设置文字
    [button setTitle:@"普通按钮" forState:UIControlStateNormal];
    
    // 1.5 设置内容图片
    [button setImage:[UIImage imageNamed:@"miniplayer_btn_playlist_normal"] forState:UIControlStateNormal];
    
    // 1.6 改变位置
    button.imageView.backgroundColor = [UIColor yellowColor];
    button.titleLabel.backgroundColor = [UIColor blueColor];
    
    // 注意: 在按钮外面改的尺寸,按钮的内部都会覆盖掉
    /*
    button.titleLabel.frame = CGRectMake(0, 0, 100, 70);
    button.imageView.frame = CGRectMake(100, 0, 70, 70);
    */
    
    [button titleRectForContentRect:CGRectMake(0, 0, 100, 70)];
    [button imageRectForContentRect:CGRectMake(100, 0, 70, 70)];
    
    [self.view addSubview:button];//不连线,就通过addSubview。
}

@end
//
//  XMGButton.h
//  09-UIButton内部子控件的调整
//

#import <UIKit/UIKit.h>

@interface XMGButton : UIButton

@end
//
//  XMGButton.m
//  09-UIButton内部子控件的调整
//

#import "XMGButton.h"

@implementation XMGButton

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
       // 文本居中
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
       // 改变图片的内容模式
        self.imageView.contentMode = UIViewContentModeCenter;
    }
    return self;
}

#pragma mark - 方式一
/**
 *  重写两个方法: 不要调用super,就是要重写掉
 *  contentRect: 内容的尺寸,内容包括(imageView和label)
 */
/*
- (CGRect)titleRectForContentRect:(CGRect)contentRect{
    return CGRectMake(0, 0, 100, 70);
}

- (CGRect)imageRectForContentRect:(CGRect)contentRect{
    return CGRectMake(100, 0, 70, 70);
}
  */



#pragma mark - 方式二
- (void)layoutSubviews{
    [super layoutSubviews];
    // 设置子控件的位置
    self.titleLabel.frame = CGRectMake(0, 0, 100, 70);
    self.imageView.frame = CGRectMake(100, 0, 70, 70);
}

@end

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值