我是斯威夫特的新手,非常感谢我能得到的所有帮助! 我的应用程序有两个ViewControllers,第一个询问“你感觉如何?”并通过按钮提供替代方案。当点击其中一个按钮时,会输入ViewController2并显示标签。
我在ViewController2中为每个按钮随机显示了不同的文本数组。我的问题是,每个应该属于一个特定按钮的不同数组,但无论哪个按钮“属于”,它们都会混合显示。这混合了文本,它们不再属于自己的按钮/替代品。
override func viewDidLoad() {
super.viewDidLoad()
//the ViewController2 has just been entered by clicking any button in ViewController1
TextForButton1: NSArray =
["EX1", "EX2", "EX3"]
let rangeButton1: UInt32 = UInt32(TextForButton1.count)
let randomNumberButton1 = Int(arc4random_uniform(rangeButton1))
let StringButton1 = Button1.objectAtIndex(randomNumberButton1)
self.Label.text = QuoteStringNervous as? String
//New Button= supposed to be its own text
let TextForButton2: NSArray = ["EX4", "EX5", "EX6"]
let rangeButton2: UInt32 = UInt32(TextForButton2.count)
let randomNumberButton2 = Int(arc4random_uniform(rangeButton2))
let StringButton2 = TextForButton2.objectAtIndex(randomNumberButton2)
self.Label.text = QuoteStringFrustrated as? String
问题的例子是:点击Button1时,可以显示“EX4”/“EX5”/“EX6”,而不只是“EX1”/“EX2”/“EX3”。 < / p>
我知道UIButtons必须包含在代码中,但在哪里?我试图在ViewController2中拖动按钮并创建新动作,但它不起作用。
请帮帮我: - )
答案 0 :(得分:1)
对于您的示例,最好为每个按钮使用segue。然后在第一个视图控制器中,您可以确定激活segue的按钮,并使用prepareForSegue修改destinationViewController中的按钮标题。
例如,将按钮拖动到视图控制器1中,将segue动作添加到当前视图控制器2中。
在视图控制器1的代码中,添加prepareForSegue,添加2按钮IBOutlets,并将iboutlet连接到故事板。
还为每个按钮的TouchUpInside添加一个IBAction,它将控制器1中的变量设置为按下的按钮。
现在在prepareForSegue中检查按下的按钮,并根据它是哪一个在视图控制器2中设置文本数组
至于你在不同视图控制器中触发动作的实际问题......
还有NSNotification
在来电者中:
[[NSNotificationCenter defaultCenter] postNotificationNamed:@"DoSomethingNotification" userInfo:nil];
在接收者的viewDidLoad
中[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething:) forNotificationNamed:@"DoSomethingNotification"]]
并将该功能添加到接收器
-(void)doSomething:(NSNotification*)sender {
// Perform action here
}
不要忘记将此添加到接收器:
-dealloc {
[NSNotificationCenter defaultCenter] removeObserver:self];
}
答案 1 :(得分:0)
1)你不应该在Swift中真正使用NSArrays ...... 2)查看代表:
http://code.tutsplus.com/tutorials/swift-from-scratch-delegation-and-properties--cms-23445
iOS平台上的编程基于代表,因此学习它们是解决问题的第一步。