|
import
UIKit
@H_301_82@
class
ViewController
:
UIViewController
,
UITextFieldDelegate
{
@IBOutlet
weak
var
button:
UIButton
!
textField:
UITextField
!
override
func
viewDidLoad() {
super
.viewDidLoad()
textField.delegate =
self
}
textField(textField:
NSRange
replacementString string:
String
) ->
Bool
{
let
newText = textField.text!.stringByReplacingCharactersInRange(
range.toRange(textField.text!),withString: string)
button.enabled = newText.characters.count > 0
return
true
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
//扩展NSRange,让swift的string能使用stringByReplacingCharactersInRange
extension
{
toRange(string:
Range
<
.
Index
> {
startIndex = string.startIndex.advancedBy(
self
.location)
endIndex = startIndex.advancedBy(
.length)
startIndex..<endIndex
}
}
|
var s="1234567890"
var ns1=(s as NSString).substringFromIndex(5)
var ns2=(s NSString).substringToIndex(4)
var ns3=(s NSString).substringWithRange(NSMakeRange(4,1))
println(ns1)//67890
println(ns2)//1234
println(ns3)//5
2.直接调用String
的对应方法(推荐使用该方法),由于String
对应的方法参数是String.Index
类型而非Int
类型,所以我们首先要创建String.Index
类型参数值,204)">// var s="1234567890"
// let index = advance(s.startIndex,5) swift 1.x
//let index2 = advance(s.endIndex,-6); swift 1.x
let index = s.startIndex.advancedBy(5) //swift 2.0+
let index2 = s.endIndex.advancedBy(-6) var range = Range<String.Index>(start: index2,end: index)
var s1:String=s.substringFromIndex(index)
var s2:String=s.substringToIndex(index2)
var s3=s.substringWithRange(range)
print(s1)print(s2)print(s3)//5
// 扩展String
extension String {
subscript (r: Int>) -> String {
get {
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = self.startIndex.advancedBy(r.endIndex)
return self[Range(start: startIndex,end: endIndex)]
}
}
}
var s4 = s[2...4]
print(s4);//345
通过String
定义可以看出属性Index
是个结构体,具体代码如下:
String : CollectionType {
struct Index : BidirectionalIndexType,Comparable,153)">Reflectable {
func successor() -> Index
func predecessor() -> func getMirror() -> MirrorType
}
var startIndex: Index { get }
var endIndex: subscript (i: Index) -> Character { get }
func generate() -> IndexingGenerator<String>
}