【问题标题】:If statements for code generated buttons, Swift代码生成按钮的 if 语句,Swift
【发布时间】:2015-06-10 00:07:40
【问题描述】:

我在 Staked Overflow 上阅读了很多内容,并观看了有关使用代码生成按钮的 youtube 视频,但我不知道如何根据按钮创建 if 语句。这是嵌套在另一条语句中的,因为当使用原始的是或否按钮回答一个问题时,我会问另一个问题。

我有:

var btn = UIButton(frame: CGRectMake(50, 50, 150, 20));
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
btn.setTitle("My Button Text!!", forState:UIControlState.Normal);
btn.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside);
self.view.addSubview(btn);

func buttonTapped(sender: UIButton!) {
    println("Button Tapped!!!")
}

但不是打印“Button Tapped!!!”我收到“SIGABART”错误。我如何使用 if 语句而不是函数语句?有没有更好的方法来编写这个函数语句?

完整代码为:

//
//  ViewController.swift
//  Living Vermont
//
//  Created by Matthew Furtsch on 6/8/15.
//  Copyright (c) 2015 Matthew Furtsch. All rights reserved.
//

import UIKit

class ViewController: UIViewController {


    var label1: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.



        label1 = UILabel()
        label1.text = "Is it a plant?"
        label1.font = UIFont.systemFontOfSize(36)
        label1.sizeToFit()
        //Label location quardnets
        label1.center = CGPoint(x: 100, y: 0)
        view.addSubview(label1)
        UIView.animateWithDuration(1.5, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.0, options: nil, animations: {
            self.label1.center = CGPoint(x: 100, y: 0 + 40)
        }, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func journal(sender: AnyObject)
    {

    }
    @IBAction func noButton(sender: AnyObject)
    {
        label1.text = "no"
        var btn = UIButton(frame: CGRectMake(50, 50, 150, 20));
        btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal);
        btn.setTitle("My Button Text!!", forState:UIControlState.Normal);
        btn.addTarget(self, action: "buttonTapped:", forControlEvents: UIControlEvents.TouchUpInside);
        self.view.addSubview(btn);

         func buttonTapped(sender: UIButton!) {
            println("Button Tapped!!!")
        }
    }
    @IBAction func yesButton(sender: AnyObject)
    {

        label1.text = "yes"
         }
}

【问题讨论】:

  • 如果您收到 SIGABRT,解释中止原因的相关错误消息是什么?请提供消息和堆栈跟踪。
  • 您提供的代码对我来说完全没问题。也许这是 Xcode 中的一个错误...尝试重新启动它。

标签: swift if-statement uibutton sigabrt


【解决方案1】:

我的猜测是您的 buttonTapped 函数嵌套在另一个方法中,例如 viewDidLoad。它必须是视图控制器类的顶级方法。将 buttonTapped 方法向上移动,使其位于类中,但不在类中的任何方法中。

您应该编辑您的问题并包含您收到的整个崩溃消息以及堆栈跟踪。这可能有助于我们判断出了什么问题。

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 2023-03-19
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2014-10-16
    • 2013-05-16
    相关资源
    最近更新 更多