私はUITexfieldsを持っていますが、数値を入力する他のショーアラートのみの番号を受け入れる必要があります。 motionSicknessTextFiledは数字のみを受け入れる必要がある
NSString*dogswithMotionSickness=motionSicknessTextField.text;
NSString*valueOne=cereniaTextField.text;
NSString*valueTwo=prescriptionTextField.text;
NSString*valueThree=otherMeansTextField.text;
NSString*valueFour=overtheCounterTextField.text;
これらの値を取得するUITextFieldで、誰かがテキストフィールド内をタッチしたときに表示するキーボードの種類を指定できます。
例えば。数字のみのキーボード。
このスクリーンショットのように:
これは、XIBとXcodeに組み込まれたInterface Builderを使用して作業するときに簡単に設定できますが、プログラムでこれを理解したい場合は、Appleの UITextInputTraits
プロトコルリファレンスページ、特にkeyboardType
property 情報。
句読点を除外するには、テキストフィールドのデリゲートを設定し、shouldChangeCharactersInRangeメソッドを設定します。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
return stringIsValid;
}
目的C
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (!string.length)
return YES;
if (textField == self.tmpTextField)
{
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
options:NSRegularExpressionCaseInsensitive
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
options:0
range:NSMakeRange(0, [newString length])];
if (numberOfMatches == 0)
return NO;
}
return YES;
}
Swift 3.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if !string.characters.count {
return true
}
do {
if textField == self.tmpTextField {
var newString = textField.text.replacingCharacters(inRange: range, with: string)
var expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$"
var regex = try NSRegularExpression(pattern: expression, options: NSRegularExpressionCaseInsensitive)
var numberOfMatches = regex.numberOfMatches(inString: newString, options: [], range: NSRange(location: 0, length: newString.characters.count))
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
}
return true
}
[textField setKeyboardType:UIKeyboardTypeNumberPad];
コードはUITextField
デリゲートメソッドです。このスニペットを使用する前に、次のプロパティが必要です。
self.maxCharacters
self.numeric
// int文字のみ。self.decimalNumeric
//数字と「。」、「、」のみ(ロシア語などの特定のロケール用)。- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(self.numeric || self.decimalNumeric)
{
NSString *fulltext = [textField.text stringByAppendingString:string];
NSString *charactersSetString = @"0123456789";
// For decimal keyboard, allow "dot" and "comma" characters.
if(self.decimalNumeric) {
charactersSetString = [charactersSetString stringByAppendingString:@".,"];
}
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:charactersSetString];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:fulltext];
// If typed character is out of Set, ignore it.
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
if(!stringIsValid) {
return NO;
}
if(self.decimalNumeric)
{
NSString *currentText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Change the "," (appears in other locale keyboards, such as russian) key ot "."
currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."];
// Check the statements of decimal value.
if([fulltext isEqualToString:@"."]) {
textField.text = @"0.";
return NO;
}
if([fulltext rangeOfString:@".."].location != NSNotFound) {
textField.text = [fulltext stringByReplacingOccurrencesOfString:@".." withString:@"."];
return NO;
}
// If second dot is typed, ignore it.
NSArray *dots = [fulltext componentsSeparatedByString:@"."];
if(dots.count > 2) {
textField.text = currentText;
return NO;
}
// If first character is zero and second character is > 0, replace first with second. 05 => 5;
if(fulltext.length == 2) {
if([[fulltext substringToIndex:1] isEqualToString:@"0"] && ![fulltext isEqualToString:@"0."]) {
textField.text = [fulltext substringWithRange:NSMakeRange(1, 1)];
return NO;
}
}
}
}
// Check the max characters typed.
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= _maxCharacters || returnKey;
}
マイケル・ダウターマンの答えを修正:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(string.length > 0)
{
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
return stringIsValid;
}
return YES;
}
Swift 4
これは数字の入力のみを許可し、文字制限を設定することもできます
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
if string == numberFiltered {
let currentText = textField.text ?? ""
guard let stringRange = Range(range, in: currentText) else { return false }
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
return updatedText.count <= 10
} else {
return false
}
}
Swiftソリューション:
ViewDidLoadでデリゲートを設定します。
_yourTextField.delegate = self
let _acceptableCharacters = "0123456789."
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if (string.characters.count == 0) {
return true
}
if (textField == self._yourTextField) {
let cs = NSCharacterSet(charactersInString: self._acceptableCharacters)
let filtered = string.componentsSeparatedByCharactersInSet(cs).filter { !$0.isEmpty }
let str = filtered.joinWithSeparator("")
return (string != str)
}
return true
}
これは、文字列に数値のみが含まれているかどうかをチェックする関数です
+(BOOL) checkforNumeric:(NSString*) str
{
NSString *strMatchstring=@"\\b([0-9%_.+\\-]+)\\b";
NSPredicate *textpredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@", strMatchstring];
if(![textpredicate evaluateWithObject:str])
{
//////NSLog(@"Invalid email address found");
UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"please enter valid text." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close",nil];
[objAlert show];
[objAlert release];
return FALSE;
}
return TRUE;
}
送信ボタンで確認してください。
この答え Swift 3でエラーを投げました、ここに実際の答えがあります:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.characters.count == 0 {
return true
}
do {
if textField == self.numberTextField {
let nString = textField.text as NSString?
let newString = nString?.replacingCharacters(in: range, with: string)
let expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$"
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!))
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
}
return true
}
@ almas-adlibekによるベストアンサーのSwift 4.2ポート
構成変数の束:
private let kMaxTextLength = 8
private let kZeroDotted = "0."
private let kZero = "0"
private let kDoubleDot = ".."
private let kDot = "."
private let kPeriod = ","
ここで、Swift 4はコードの一部を変換しました。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let swiftRange = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: swiftRange, with: string)
var currentText = textField.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
// Change the "," (appears in other locale keyboards, such as russian) key ot "."
currentText = currentText?.replacingOccurrences(of: kPeriod, with: kDot)
// Check the statements of decimal value.
if (newText == kDot) {
textField.text = kZeroDotted;
return false
}
if (newText.range(of: kDoubleDot) != nil) {
textField.text = newText.replacingOccurrences(of: kDoubleDot, with: kDot);
return false
}
// If second dot is typed, ignore it.
let dots = newText.components(separatedBy: kDot)
if(dots.count > 2) {
textField.text = currentText;
return false
}
// If first character is zero and second character is > 0, replace first with second. 05 => 5;
if(newText.count == 2) {
if(newText[0...0] == kZero && newText != kZeroDotted) {
textField.text = newText[1...1]
return false
}
}
// Check the max characters typed.
let oldLength = textField.text?.count ?? 0
let replacementLength = string.count
let rangeLength = range.length
let newLength = oldLength - rangeLength + replacementLength;
let returnKey = string.rangeOfCharacter(from: CharacterSet.newlines) != nil
return newLength <= kMaxTextLength || returnKey;
}
Michaelの答えを修正し、実装を少し簡単にしました。 UITextfield
のデリゲートがそれ自体に設定されていることを確認してください。
yourTxtField.delegate = self;
さらに、このコードをコピーしてメインファイルに貼り付けます。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == yourTxtField) {
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
return stringIsValid;
}else {
return YES;
}
}
スペースバーの使用を許可する場合は、CharactersInString
の末尾の空白スペースに置くだけで、次のようになります。
@"0123456789" -> @"0123456789 "
文字列の長さを制限する場合は、if関数を次のように置き換えます。
if (textField == yourTxtField) {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return (([string isEqualToString:filtered])&&(newLength <= 10));
}
私の場合、末尾の「10」は文字の制限を表しています。
乾杯! :)