限制 Text Field 输入的内容类型:只允许输入数字

效果如下:

 

ViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface ViewController : UIViewController<UITextFieldDelegate>
4 @property (strong, nonatomic) IBOutlet UITextField *txtLimitInput;
5 
6 @end

ViewController.m

  1 #import "ViewController.h"
  2 
  3 @interface ViewController ()
  4 - (void)layoutUI;
  5 - (BOOL)validateNumberByASCII:(NSString *)string;
  6 - (BOOL)validateNumberByRange:(NSString *)string;
  7 - (BOOL)validateNumberByRegExp:(NSString *)string;
  8 @end
  9 
 10 @implementation ViewController
 11 
 12 - (void)viewDidLoad {
 13     [super viewDidLoad];
 14     
 15     [self layoutUI];
 16 }
 17 
 18 - (void)didReceiveMemoryWarning {
 19     [super didReceiveMemoryWarning];
 20     // Dispose of any resources that can be recreated.
 21 }
 22 
 23 - (void)layoutUI {
 24     _txtLimitInput.placeholder = @"请输入数字";
 25     
 26     //第一种方式:设置键盘类型
 27     //_txtLimitInput.keyboardType = UIKeyboardTypeDecimalPad;
 28     
 29     //第二种方式:通过 UITextFieldDelegate 的 shouldChangeCharactersInRange: 方法
 30     _txtLimitInput.delegate = self;
 31 }
 32 
 33 #pragma mark - 三种判断字符串内容是否是有效数字的方式
 34 /**
 35  *  『ASCII码』判断字符串内容是否是有效数字
 36  *
 37  *  @param string 需要验证的字符串
 38  *
 39  *  @return 字符串内容是否是有效数字
 40  */
 41 - (BOOL)validateNumberByASCII:(NSString *)string {
 42     BOOL isValid = YES;
 43     NSUInteger len = string.length;
 44     if (len > 0) {
 45         for (NSUInteger i=0; i<len; i++) {
 46             NSUInteger asciiCode = [string characterAtIndex:i];
 47             if (asciiCode < 48 || asciiCode > 57) {
 48                 isValid = NO;
 49                 break;
 50             }
 51         }
 52     }
 53     return isValid;
 54 }
 55 
 56 /**
 57  *  『字符范围』判断字符串内容是否是有效数字
 58  *
 59  *  @param string 需要验证的字符串
 60  *
 61  *  @return 字符串内容是否是有效数字
 62  */
 63 - (BOOL)validateNumberByRange:(NSString *)string {
 64     BOOL isValid = YES;
 65     NSUInteger len = string.length;
 66     if (len > 0) {
 67         NSCharacterSet *validNumberCS = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
 68         NSUInteger singleStrIndex = 0;
 69         do {
 70             NSString *singleStr = [string substringWithRange:NSMakeRange(singleStrIndex, 1)];
 71             NSRange range = [singleStr rangeOfCharacterFromSet:validNumberCS];
 72             if (range.length == 0) {
 73                 isValid = NO;
 74                 break;
 75             }
 76             singleStrIndex++;
 77         } while (singleStrIndex < len);
 78     }
 79     return isValid;
 80 }
 81 
 82 /**
 83  *  『正则表达式;推荐使用,不用循环遍历,控制更灵活』判断字符串内容是否是有效数字
 84  *
 85  *  @param string 需要验证的字符串
 86  *
 87  *  @return 字符串内容是否是有效数字
 88  */
 89 - (BOOL)validateNumberByRegExp:(NSString *)string {
 90     BOOL isValid = YES;
 91     NSUInteger len = string.length;
 92     if (len > 0) {
 93         NSString *numberRegex = @"^[0-9]*$";
 94         NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
 95         isValid = [numberPredicate evaluateWithObject:string];
 96     }
 97     return isValid;
 98 }
 99 
100 #pragma mark - UITextFieldDelegate
101 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
102     //return [self validateNumberByASCII:string];
103     //return [self validateNumberByRange:string];
104     return [self validateNumberByRegExp:string]; //推荐方式
105 }
106 
107 @end

Main.storyboard

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
 2 <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="vXZ-lx-hvc">
 3     <dependencies>
 4         <deployment identifier="iOS"/>
 5         <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
 6     </dependencies>
 7     <scenes>
 8         <!--View Controller-->
 9         <scene sceneID="ufC-wZ-h7g">
10             <objects>
11                 <viewController id="vXZ-lx-hvc" customClass="ViewController" sceneMemberID="viewController">
12                     <layoutGuides>
13                         <viewControllerLayoutGuide type="top" id="jyV-Pf-zRb"/>
14                         <viewControllerLayoutGuide type="bottom" id="2fi-mo-0CV"/>
15                     </layoutGuides>
16                     <view key="view" contentMode="scaleToFill" id="kh9-bI-dsS">
17                         <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
18                         <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
19                         <subviews>
20                             <textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="mb3-C5-UpN">
21                                 <rect key="frame" x="200" y="285" width="200" height="30"/>
22                                 <constraints>
23                                     <constraint firstAttribute="width" constant="200" id="8dl-R0-OzV"/>
24                                 </constraints>
25                                 <fontDescription key="fontDescription" type="system" pointSize="14"/>
26                                 <textInputTraits key="textInputTraits"/>
27                             </textField>
28                             <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="限制 Text Field 输入的内容类型" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8zf-7E-ija">
29                                 <rect key="frame" x="200" y="255" width="196" height="17"/>
30                                 <fontDescription key="fontDescription" type="system" pointSize="14"/>
31                                 <color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
32                                 <nil key="highlightedColor"/>
33                             </label>
34                         </subviews>
35                         <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
36                         <constraints>
37                             <constraint firstItem="mb3-C5-UpN" firstAttribute="centerX" secondItem="kh9-bI-dsS" secondAttribute="centerX" id="Dh5-bw-2LN"/>
38                             <constraint firstItem="mb3-C5-UpN" firstAttribute="centerY" secondItem="kh9-bI-dsS" secondAttribute="centerY" id="Lby-hq-mya"/>
39                             <constraint firstItem="mb3-C5-UpN" firstAttribute="leading" secondItem="8zf-7E-ija" secondAttribute="leading" id="SyI-SC-iNN"/>
40                             <constraint firstItem="mb3-C5-UpN" firstAttribute="top" secondItem="8zf-7E-ija" secondAttribute="bottom" constant="13" id="yuO-kC-OCZ"/>
41                         </constraints>
42                     </view>
43                     <connections>
44                         <outlet property="txtLimitInput" destination="mb3-C5-UpN" id="cYi-Ep-sWq"/>
45                     </connections>
46                 </viewController>
47                 <placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
48             </objects>
49         </scene>
50     </scenes>
51 </document>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值