Simple steps for IOS uitextfield input length control

Source: Internet
Author: User

In the iOS development process, we sometimes need to control the input length of the Uitextfield, such as the maximum length of the input mobile phone number 11 bits, and iOS itself is not like Android can set input box input length, followed by a few simple steps to achieve this function:

1. Create a new class to continue Uitextfield such as this class called Myuitextfield

2. Declare a variable to record the maximum length of the input

3. Add an event to listen for changes in input box input values

4. Intercept the string by judging whether the length of the current text string is greater than the maximum length and assign a value to the current text to guarantee that the value of the text string starts with the specified maximum length

The code is as follows:

Import UIKit

Class MyTextField: uitextfield{

The maximum length of the Var maxlength=11//can be entered

override init(frame: cgrect) {

Super. Init(frame:frame)

self. Addevent()

}

Required init? ( Coder Adecoder: nscoder) {

Super. Init(coder:adecoder)

self. Addevent()

}

// Add event to listen for changes in input box values

func addevent () {

self. AddTarget(self, action: #selector(valuechage), for:. editingchanged)

}

// limit input length of input box

func valuechage () {

if (self. Text?. characters. Count)!>maxLength{

let idx = self. Text?. index(text?. startIndex)!, Offsetby: maxLength)

self. Text=self. Text?. substring(to:idx!)

}

}

}

Simple steps for IOS uitextfield input length control

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.