實現(xiàn)一個簡單的button 先給出github鏈接
效果:
需求:
點擊宣旱,隱藏button上文字淫半,將顯示一個菊花擎颖,表示正在處理網(wǎng)絡(luò)請求或者其他任務
再次點擊,顯示button文字绊汹,菊花停止轉(zhuǎn)動,恢復最初狀態(tài)
主要一下幾個步驟:
- 創(chuàng)建一個button的子類
- 給button添加一個UIActivityIndicatorView(俗稱菊花)
- 在特定的時機扮宠,開啟關(guān)閉旋轉(zhuǎn)
代碼:
創(chuàng)建button子類西乖,PZLoadingButton
#import <UIKit/UIKit.h>
@interface PZLoadingButton : UIButton
- (void)startLoading;
- (void)stopLoading;
@end
需要兩個接口,一個開始loading坛增,一個停止loading
具體實現(xiàn)如下:
@property (nonatomic, strong) UIActivityIndicatorView * indecator;
- (void)startLoading {
self.titleLabel.alpha = 0;
[self.indecator startAnimating];
}
- (void)stopLoading {
self.titleLabel.alpha = 1;
[self.indecator stopAnimating];
}
那我們在button創(chuàng)建的時候?qū)IActivityIndicatorView添加到button上获雕,添加button要考慮以下情況:
- 使用xib或storyboard + autolayout
xib和 autolayout拖控件方式會調(diào)用- (id)initWithCoder:(NSCoder *)aDecoder
方法- 使用代碼 + frame
純代碼使用便利構(gòu)造器+ (id)buttonWithType:(UIButtonType)buttonType
會調(diào)用- (instancetype)initWithFrame:(CGRect)frame
方法
分別對應以下兩種初始化方法:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self commentInit];
[self setupConstrains];
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self commentInit];
[self setupConstrains];
}
return self;
}
因為創(chuàng)建的菊花默認狀態(tài)下是顯示的,
- (void)commentInit
方法主要功能就是將其隱藏收捣。
- (void)commentInit {
self.indecator.hidden = YES;
self.indecator.userInteractionEnabled = NO;
self.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
self.contentHorizontalAlignment =UIControlContentHorizontalAlignmentCenter;
}
- (void)setupConstrains {
//X方向居中
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.indecator attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
//Y方向居中
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.indecator attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
//寬25
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.indecator attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:25]];
//高25
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.indecator attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:0 multiplier:1 constant:25]];
}
到此為止届案,詳細功能見代碼