[图片上传中...(Untitled.gif-8c0db8-1516886932787-0)]
先看效果
Untitled.gif
1.加入最大值最小值判断
2.可以设置初始值
3.代理和block两种回调
主要代码:
- (void)textChange: (NSNotification *)noti {
NSInteger count = self.text.integerValue;
if (count >= self.maxCount) {
self.rightButton.enabled = NO;
self.leftButton.enabled = YES;
self.text = [NSString stringWithFormat:@"%ld",(long)self.maxCount];
}else if (count == self.minCount) {
self.leftButton.enabled = NO;
self.rightButton.enabled = YES;
} else if (count < self.maxCount && count > self.minCount) {
self.leftButton.enabled = YES;
self.rightButton.enabled = YES;
}
if (self.countFielddDelegate && [self.countFielddDelegate respondsToSelector:@selector(countField:count:)]) {
[self.countFielddDelegate countField:self count:self.text.integerValue];
}
if (self.countBlock) {
self.countBlock(self.text.integerValue);
}
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self];
}
- (void)setCount:(NSInteger)count {
_count = count;
self.text = [NSString stringWithFormat:@"%ld",(long)count];
}
- (void)clickButton: (UIButton *)button {
button.selected = !button.selected;
NSInteger count = self.text.integerValue;
if (button.tag == GHCountFieldButtonType_add) {
if (count < self.maxCount) {
count++;
button.enabled = YES;
if (count ==self.maxCount) {
button.enabled = NO;
}
self.leftButton.enabled = YES;
}
} else if (button.tag == GHCountFieldButtonType_sub) {
if (count > self.minCount) {
count--;
if (count == self.minCount) {
button.enabled = NO;
}
self.rightButton.enabled = YES;
} else {
button.enabled = YES;
}
}
self.text = [NSString stringWithFormat:@"%ld",(long)count];
if (self.countFielddDelegate && [self.countFielddDelegate respondsToSelector:@selector(countField:count:)]) {
[self.countFielddDelegate countField:self count:self.text.integerValue];
}
if (self.countBlock) {
self.countBlock(self.text.integerValue);
}
}
构造方法
GHCountField *countField = [[GHCountField alloc]initWithFrame:CGRectMake(100, 100, 100, 40)];
countField.count = 4;
countField.maxCount = 10;
countField.countFielddDelegate = self;
countField.countBlock = ^(NSInteger count) {
NSLog(@"回调 :%ld",(long)count);
};
[self.view addSubview:countField];
代理方法
- (void)countField:(GHCountField *)countField count:(NSInteger)count {
NSLog(@"代理:%ld",(long)count);
}
网友评论