【问题标题】:Fixed UITextField's character length [duplicate]修复了 UITextField 的字符长度 [重复]
【发布时间】:2018-09-11 14:31:35
【问题描述】:

如何在不使用委托方法的情况下限制UITextField 的字符。我使用UITableView,其中我在单元格中有UITextField,并在同一屏幕内的不同位置使用,我想将文本字段限制在某个位置UITableViewCell。任何帮助将不胜感激。

【问题讨论】:

    标签: ios objective-c iphone


    【解决方案1】:

    前段时间我遇到了同样的问题。但是,不使用代表不是正确的方法。您应该使用委托并根据位置控制行为。

    1. 在你的 tableViewCell 类中创建一个函数,假设是

      -(void)setMyCellTag:(NSInteger)tag
      {
          self.tag = tag;
      }
      
    2. 现在从你的 cellForRowAtIndexPath 函数调用这个方法,

      [cell setMyCellTag:indexPath.row];
      
    3. 在 UITextField 委托方法中使用条件,

      if(self.tag == yourposition)
      {
         //Do Something
      }
      

    简单。感谢阅读。

    【讨论】:

    • 让我检查一下,谢谢。
    【解决方案2】:
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    {
        let currentCharacterCount = textField.text?.characters.count ?? 0
        if (range.length + range.location > currentCharacterCount){
            return false
        }
        let newLength = currentCharacterCount + string.characters.count - range.length
        return newLength <= 1 // set your limit
    }
    

    确保文本字段委托

    【讨论】:

    • @Najam 代码在标签和委托上运行良好。但我想要没有代表。
    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2019-01-05
    • 2017-08-19
    • 2012-10-23
    相关资源
    最近更新 更多