2014-10-03 4 views
1

간단한 질문을하고 싶습니다. 버튼을 만들 때 액션에 변수를 부여하려면 어떻게해야합니까?swift-- 변수 버튼 동작

경우, 버튼을 사용 생성을 위해 : 내가

NSString *selectorName = [NSString stringWithFormat:@"Button%d:",index+1]; 

[newButton addTarget:self action:NSSelectorFromString(selectorName) forControlEvents:UIControlEventTouchUpInside]; 

및 스위프트에

을 한 객체 C에

newButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside) 

를?

답변

0

변수로 Swift Selector 구조체를 저장할 수 있습니다. 당신은 선택이의 변수를 가지고 싶다면

let sel : Selector = "buttonTapped:" 
button.addTarget(self, action: sel) 

, 당신은 단순히 같은 문자열에 변수를 추가 할 수 있습니다

let sel : Selector = "button\(buttonNumber)tapped" 

이것은 StringLiteralConvertible의 선택기의 채택을 사용합니다.

셀렉터는 Using Swift With Objective C ebook에 언급되어 있습니다.

1

사용 NSSelectorFromString

let sel = NSSelectorFromString("Button\(index+1)") 

newButton.addTarget(self, action: sel, forControlEvents:UIControlEvents.TouchUpInside) 
+0

대단히 감사합니다 !!!! – user2244770