XLFormTextFieldCell.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. //
  2. // XLFormTextFieldCell.m
  3. // XLForm ( https://github.com/xmartlabs/XLForm )
  4. //
  5. // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
  6. //
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining a copy
  9. // of this software and associated documentation files (the "Software"), to deal
  10. // in the Software without restriction, including without limitation the rights
  11. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. // copies of the Software, and to permit persons to whom the Software is
  13. // furnished to do so, subject to the following conditions:
  14. //
  15. // The above copyright notice and this permission notice shall be included in
  16. // all copies or substantial portions of the Software.
  17. //
  18. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. // THE SOFTWARE.
  25. #import "NSObject+XLFormAdditions.h"
  26. #import "UIView+XLFormAdditions.h"
  27. #import "XLFormRowDescriptor.h"
  28. #import "XLForm.h"
  29. #import "XLFormTextFieldCell.h"
  30. NSString *const XLFormTextFieldLengthPercentage = @"textFieldLengthPercentage";
  31. NSString *const XLFormTextFieldMaxNumberOfCharacters = @"textFieldMaxNumberOfCharacters";
  32. @interface XLFormTextFieldCell() <UITextFieldDelegate>
  33. @property NSMutableArray * dynamicCustomConstraints;
  34. @end
  35. @implementation XLFormTextFieldCell
  36. @synthesize textField = _textField;
  37. @synthesize textLabel = _textLabel;
  38. @synthesize returnKeyType = _returnKeyType;
  39. @synthesize nextReturnKeyType = _nextReturnKeyType;
  40. #pragma mark - KVO
  41. -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  42. {
  43. if ((object == self.textLabel && [keyPath isEqualToString:@"text"]) || (object == self.imageView && [keyPath isEqualToString:@"image"])){
  44. if ([[change objectForKey:NSKeyValueChangeKindKey] isEqualToNumber:@(NSKeyValueChangeSetting)]){
  45. [self.contentView setNeedsUpdateConstraints];
  46. }
  47. }
  48. }
  49. -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  50. {
  51. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  52. if (self) {
  53. _returnKeyType = UIReturnKeyDefault;
  54. _nextReturnKeyType = UIReturnKeyNext;
  55. }
  56. return self;
  57. }
  58. -(void)dealloc
  59. {
  60. [self.textLabel removeObserver:self forKeyPath:@"text"];
  61. [self.imageView removeObserver:self forKeyPath:@"image"];
  62. }
  63. #pragma mark - XLFormDescriptorCell
  64. -(void)configure
  65. {
  66. [super configure];
  67. [self setSelectionStyle:UITableViewCellSelectionStyleNone];
  68. [self.contentView addSubview:self.textLabel];
  69. [self.contentView addSubview:self.textField];
  70. [self.contentView addConstraints:[self layoutConstraints]];
  71. [self.textLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:0];
  72. [self.imageView addObserver:self forKeyPath:@"image" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:0];
  73. [self.textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  74. }
  75. -(void)update
  76. {
  77. [super update];
  78. self.textField.delegate = self;
  79. self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
  80. if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeText]){
  81. self.textField.autocorrectionType = UITextAutocorrectionTypeDefault;
  82. self.textField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
  83. }
  84. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeName]){
  85. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  86. self.textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  87. }
  88. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeEmail]){
  89. self.textField.keyboardType = UIKeyboardTypeEmailAddress;
  90. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  91. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  92. }
  93. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeNumber]){
  94. self.textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  95. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  96. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  97. }
  98. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeInteger]){
  99. self.textField.keyboardType = UIKeyboardTypeNumberPad;
  100. }
  101. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeDecimal]){
  102. self.textField.keyboardType = UIKeyboardTypeDecimalPad;
  103. }
  104. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypePassword]){
  105. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  106. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  107. self.textField.keyboardType = UIKeyboardTypeASCIICapable;
  108. self.textField.secureTextEntry = YES;
  109. }
  110. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypePhone]){
  111. self.textField.keyboardType = UIKeyboardTypePhonePad;
  112. }
  113. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeURL]){
  114. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  115. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  116. self.textField.keyboardType = UIKeyboardTypeURL;
  117. }
  118. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeTwitter]){
  119. self.textField.keyboardType = UIKeyboardTypeTwitter;
  120. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  121. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  122. }
  123. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeAccount]){
  124. self.textField.keyboardType = UIKeyboardTypeASCIICapable;
  125. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  126. self.textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
  127. }
  128. else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeZipCode]){
  129. self.textField.autocorrectionType = UITextAutocorrectionTypeNo;
  130. self.textField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
  131. self.textField.keyboardType = UIKeyboardTypeDefault;
  132. }
  133. self.textLabel.text = ((self.rowDescriptor.required && self.rowDescriptor.title && self.rowDescriptor.sectionDescriptor.formDescriptor.addAsteriskToRequiredRowsTitle) ? [NSString stringWithFormat:@"%@*", self.rowDescriptor.title] : self.rowDescriptor.title);
  134. self.textField.text = self.rowDescriptor.value ? [self.rowDescriptor displayTextValue] : self.rowDescriptor.noValueDisplayText;
  135. [self.textField setEnabled:!self.rowDescriptor.isDisabled];
  136. self.textField.textColor = self.rowDescriptor.isDisabled ? [UIColor grayColor] : [UIColor blackColor];
  137. self.textField.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
  138. }
  139. -(BOOL)formDescriptorCellCanBecomeFirstResponder
  140. {
  141. return (!self.rowDescriptor.isDisabled);
  142. }
  143. -(BOOL)formDescriptorCellBecomeFirstResponder
  144. {
  145. return [self.textField becomeFirstResponder];
  146. }
  147. -(void)highlight
  148. {
  149. [super highlight];
  150. self.textLabel.textColor = self.tintColor;
  151. }
  152. -(void)unhighlight
  153. {
  154. [super unhighlight];
  155. [self.formViewController updateFormRow:self.rowDescriptor];
  156. }
  157. #pragma mark - Properties
  158. -(UILabel *)textLabel
  159. {
  160. if (_textLabel) return _textLabel;
  161. _textLabel = [UILabel autolayoutView];
  162. return _textLabel;
  163. }
  164. -(UITextField *)textField
  165. {
  166. if (_textField) return _textField;
  167. _textField = [UITextField autolayoutView];
  168. return _textField;
  169. }
  170. #pragma mark - LayoutConstraints
  171. -(NSArray *)layoutConstraints
  172. {
  173. NSMutableArray * result = [[NSMutableArray alloc] init];
  174. [self.textLabel setContentHuggingPriority:500 forAxis:UILayoutConstraintAxisHorizontal];
  175. [self.textLabel setContentCompressionResistancePriority:1000 forAxis:UILayoutConstraintAxisHorizontal];
  176. // Add Constraints
  177. [result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_textField]-(margin)-|"
  178. options:NSLayoutFormatAlignAllBaseline
  179. metrics:[NSDictionary dictionaryWithObjectsAndKeys:@(11.0), @"margin", nil]
  180. views:NSDictionaryOfVariableBindings(_textField)]];
  181. [result addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_textLabel]-(margin)-|"
  182. options:NSLayoutFormatAlignAllBaseline
  183. metrics:[NSDictionary dictionaryWithObjectsAndKeys:@(11.0), @"margin", nil]
  184. views:NSDictionaryOfVariableBindings(_textLabel)]];
  185. return result;
  186. }
  187. -(void)updateConstraints
  188. {
  189. if (self.dynamicCustomConstraints){
  190. [self.contentView removeConstraints:self.dynamicCustomConstraints];
  191. }
  192. NSMutableDictionary * views = [[NSMutableDictionary alloc] initWithDictionary: @{@"label": self.textLabel, @"textField": self.textField}];
  193. if (self.imageView.image){
  194. views[@"image"] = self.imageView;
  195. if (self.textLabel.text.length > 0){
  196. self.dynamicCustomConstraints = [NSMutableArray arrayWithArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[image]-[label]-[textField]-|" options:0 metrics:nil views:views]];
  197. [self.dynamicCustomConstraints addObject:[NSLayoutConstraint constraintWithItem:_textField
  198. attribute:NSLayoutAttributeWidth
  199. relatedBy:self.textFieldLengthPercentage ? NSLayoutRelationEqual : NSLayoutRelationGreaterThanOrEqual
  200. toItem:self.contentView
  201. attribute:NSLayoutAttributeWidth
  202. multiplier:self.textFieldLengthPercentage ? [self.textFieldLengthPercentage floatValue] : 0.3
  203. constant:0.0]];
  204. }
  205. else{
  206. self.dynamicCustomConstraints = [NSMutableArray arrayWithArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[image]-[textField]-|" options:0 metrics:nil views:views]];
  207. }
  208. }
  209. else{
  210. if (self.textLabel.text.length > 0){
  211. self.dynamicCustomConstraints = [NSMutableArray arrayWithArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label]-[textField]-|" options:0 metrics:nil views:views]];
  212. [self.dynamicCustomConstraints addObject:[NSLayoutConstraint constraintWithItem:_textField
  213. attribute:NSLayoutAttributeWidth
  214. relatedBy:self.textFieldLengthPercentage ? NSLayoutRelationEqual : NSLayoutRelationGreaterThanOrEqual
  215. toItem:self.contentView
  216. attribute:NSLayoutAttributeWidth
  217. multiplier:self.textFieldLengthPercentage ? [self.textFieldLengthPercentage floatValue] : 0.3
  218. constant:0.0]];
  219. }
  220. else{
  221. self.dynamicCustomConstraints = [NSMutableArray arrayWithArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[textField]-|" options:0 metrics:nil views:views]];
  222. }
  223. }
  224. [self.contentView addConstraints:self.dynamicCustomConstraints];
  225. [super updateConstraints];
  226. }
  227. #pragma mark - UITextFieldDelegate
  228. - (BOOL)textFieldShouldClear:(UITextField *)textField
  229. {
  230. return [self.formViewController textFieldShouldClear:textField];
  231. }
  232. - (BOOL)textFieldShouldReturn:(UITextField *)textField
  233. {
  234. return [self.formViewController textFieldShouldReturn:textField];
  235. }
  236. - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
  237. {
  238. return [self.formViewController textFieldShouldBeginEditing:textField];
  239. }
  240. - (BOOL)textFieldShouldEndEditing:(UITextField *)textField
  241. {
  242. return [self.formViewController textFieldShouldEndEditing:textField];
  243. }
  244. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  245. if (self.textFieldMaxNumberOfCharacters) {
  246. // Check maximum length requirement
  247. NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
  248. if (newString.length > self.textFieldMaxNumberOfCharacters.integerValue) {
  249. return NO;
  250. }
  251. }
  252. // Otherwise, leave response to view controller
  253. return [self.formViewController textField:textField shouldChangeCharactersInRange:range replacementString:string];
  254. }
  255. - (void)textFieldDidBeginEditing:(UITextField *)textField
  256. {
  257. [self.formViewController beginEditing:self.rowDescriptor];
  258. [self.formViewController textFieldDidBeginEditing:textField];
  259. // set the input to the raw value if we have a formatter and it shouldn't be used during input
  260. if (self.rowDescriptor.valueFormatter) {
  261. self.textField.text = [self.rowDescriptor editTextValue];
  262. }
  263. }
  264. - (void)textFieldDidEndEditing:(UITextField *)textField
  265. {
  266. // process text change before we stick a formatted value in the UITextField
  267. [self textFieldDidChange:textField];
  268. // losing input, replace the text field with the formatted value
  269. if (self.rowDescriptor.valueFormatter) {
  270. self.textField.text = [self.rowDescriptor.value displayText];
  271. }
  272. [self.formViewController endEditing:self.rowDescriptor];
  273. [self.formViewController textFieldDidEndEditing:textField];
  274. }
  275. #pragma mark - Helper
  276. - (void)textFieldDidChange:(UITextField *)textField{
  277. if([self.textField.text length] > 0) {
  278. BOOL didUseFormatter = NO;
  279. if (self.rowDescriptor.valueFormatter && self.rowDescriptor.useValueFormatterDuringInput)
  280. {
  281. // use generic getObjectValue:forString:errorDescription and stringForObjectValue
  282. NSString *errorDescription = nil;
  283. NSString *objectValue = nil;
  284. if ([ self.rowDescriptor.valueFormatter getObjectValue:&objectValue forString:textField.text errorDescription:&errorDescription]) {
  285. NSString *formattedValue = [self.rowDescriptor.valueFormatter stringForObjectValue:objectValue];
  286. self.rowDescriptor.value = objectValue;
  287. textField.text = formattedValue;
  288. didUseFormatter = YES;
  289. }
  290. }
  291. // only do this conversion if we didn't use the formatter
  292. if (!didUseFormatter)
  293. {
  294. if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeNumber] || [self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeDecimal]){
  295. self.rowDescriptor.value = [NSDecimalNumber decimalNumberWithString:self.textField.text locale:NSLocale.currentLocale];
  296. } else if ([self.rowDescriptor.rowType isEqualToString:XLFormRowDescriptorTypeInteger]){
  297. self.rowDescriptor.value = @([self.textField.text integerValue]);
  298. } else {
  299. self.rowDescriptor.value = self.textField.text;
  300. }
  301. }
  302. } else {
  303. self.rowDescriptor.value = nil;
  304. }
  305. }
  306. -(void)setReturnKeyType:(UIReturnKeyType)returnKeyType
  307. {
  308. _returnKeyType = returnKeyType;
  309. self.textField.returnKeyType = returnKeyType;
  310. }
  311. -(UIReturnKeyType)returnKeyType
  312. {
  313. return _returnKeyType;
  314. }
  315. @end