2017-08-28 81 views
1

我有代碼來實現「粘貼」功能。粘貼(插入)到標籤(IOS)只有數字字符串

但有一個插入的所有符號,而不僅是數字。

我怎樣才能讓它只能插入數字?

創建擴展文件:

Swift extension example

Past (Photo)

更新代碼

actionSheetController.addAction(
     UIAlertAction(title: NSLocalizedString("Past", comment: ""), style: .default, handler: { [weak self] _ in 
      guard let strongSelf = self else { return } 

      strongSelf.displayResultLabel.text = UIPasteboard.general.string.onlyNumbers() 

      print ("Past") 

     }) 
    ) 



extension String { 

    func onlyNumbers() ->String{ 
     do{ 
      let regex = try NSRegularExpression(pattern: "([//.,\\d])*", options:[.dotMatchesLineSeparators]) 
      var result : String = "" 

      for resultMatch in regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, NSString(string: self).length)) { 
       result += NSString(string: self).substring(with: resultMatch.range) 
      } 
      return result 
     } 
     catch 
     { 

     } 

     return "" 
    } 

} 
+0

字符串轉換爲數字和後背,或使用NSCharacterSet從字符串中提取數字。 – Brandon

回答

0

使用此extensionregex函數來獲取Ø NLY您String

extension String { 

    func onlyNumbers() ->String{ 
     do{ 
      let regex = try NSRegularExpression(pattern: "([//.,\\d])*", options:[.dotMatchesLineSeparators]) 
      var result : String = "" 

      for resultMatch in regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, NSString(string: self).length)) { 
       result += NSString(string: self).substring(with: resultMatch.range) 
      } 
      return result 
     } 
     catch 
     { 

     } 

     return "" 
    } 

} 

的號碼,你可以使用它像這樣

actionSheetController.addAction(
     UIAlertAction(title: NSLocalizedString("Past", comment: ""), style: .default, handler: { [weak self] _ in 
      guard let strongSelf = self else { return } 

      strongSelf.displayResultLabel.text = UIPasteboard.general.string.onlyNumbers() 
      print ("Past") 

     }) 
    ) 
+0

有錯誤:字符串「String?」的值沒有成員「onlyMembers」,聲明只在文件範圍 – BLC

+0

有效您需要爲String添加擴展名,您是否這樣做? @BLC –

+0

@BLC該方法被稱爲onlyNumbers()不僅會員可能是一個錯字請檢查這是之前測試過的帖子 –