【Objective-C】在 UIButton 上添加 UIActivityIndicator 及设置大小

开发中会遇到点击一个按钮,按钮上就多一个系统的小菊花,来示操作正在进行,例如下面的加好友按钮:


直接上代码

    // 初始化按钮
    UIButton *addFriendButton = [UIButton emptyFrameView];
    addFriendButton.layer.masksToBounds = YES;
    addFriendButton.layer.cornerRadius = 4.f;
    addFriendButton.layer.borderWidth = 0.5f;
    addFriendButton.layer.borderColor = [[UIColor green1Color] CGColor];
    addFriendButton.titleLabel.font = [UIFont systemFontOfSize:12.1];
    [addFriendButton setBackgroundColor:[UIColor white1Color]];
    [addFriendButton setTitle:@"+好友" forState:UIControlStateNormal];
    [addFriendButton addTarget:self action:@selector(didClickAddFriend:) forControlEvents:UIControlEventTouchUpInside];
- (IBAction)didClickAddFriend:(id)sender{
    // 将文字置空
    [self.addFriendButton setTitle:nil forState:UIControlStateNormal];
    // 初始化系统小菊花
    UIActivityIndicatorView *addFriendActivityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:self.addFriendButton.bounds];
    [addFriendActivityIndicator setUserInteractionEnabled:YES];
    [addFriendActivityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    // 改变小菊花颜色
    [addFriendActivityIndicator setColor:[UIColor green1Color]];
    // 下文去解释下面这两行行代码的作用
    // CGAffineTransform transform = CGAffineTransformMakeScale(.7f, .7f);
    // addFriendActivityIndicator.transform = transform;
    [self.addFriendButton addSubview:addFriendActivityIndicator];
    // 小菊花开始转圈圈
    [addFriendActivityIndicator startAnimating];
    // 用block实现加好友操作
    if ([self addFriendHandler]) {
        self.addFriendHandler();
    }
}

UIActivityIndicatorView 不能自定义大小,创建的 UIActivityIndicatorView 有三种 style,这三种 style 有默认的大小,不能通过设置 frame 的方式来修改大小,那么上面代码中注释的那一行就起作用了。
需求:需要把显示的 UIActivityIndicatorView 显示得比预定义的小,实现的方式是通过 transform 来修改显示 UIActivityIndicatorView 的显示大小。

    CGAffineTransform transform = CGAffineTransformMakeScale(.7f, .7f);
    addFriendActivityIndicator.transform = transform;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,246评论 4 61
  • 双十二刚过又是平安夜和圣诞节,购物一波赶着一波,停也停不下来!买了好牌即食枣,不错,喜欢吃这种没有过度加工的...
    公主殿下_阅读 274评论 0 0
  • 2017.09.28 周四 晴 给儿子检查作业,一上来就出现了问题。心理上就有些上火,无名的怒气就要发作。狠狠的对...
    戴骁勇阅读 378评论 0 0
  • 被隔壁洗衣机洗衣服的声音吵醒,那巨大的声音如同海浪拍打樵石,把熟睡中的我扯醒了。 阳光轻轻一层打在我的房间一角,而...
    BU3001阅读 277评论 0 0
  • Markdown 的设计哲学 Markdown 的目標是實現「易讀易寫」。不過最需要強調的便是它的可讀性。一份使用...
    寒桥阅读 596评论 0 1