使用单独文件中的子类UIButton更改视图控制器的背景

时间:2019-01-31 08:06:10

标签: ios swift

我是Swift / iOS编程的初学者。我正在尝试以编程方式执行操作。我在单独的swift文件中创建了UIButton的子类。我的目标是仅更改基础ViewController的背景。

CustomButton.swift

import UIKit

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.backgroundColor = .blue
        self.setTitleColor(.white, for: .normal)
        self.setTitle("Press Me", for: .normal)
        self.layer.cornerRadius = 15
        // Button Action
        self.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)

    }

    @objc func buttonPressed() {
        // Verify the method is called when the button is pressed
        self.setTitle("Pressed", for: .normal)
        // Change the background color for the ViewController
        let vc = ViewController()
        vc.view.backgroundColor = .red
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

ViewController.swift

import UIKit

class ViewController: UIViewController{

    let myButton = CustomButton()

    fileprivate func addElements() {
        view.addSubview(myButton)

        myButton.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 60).isActive = true
        myButton.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -60).isActive = true
        myButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 400).isActive = true
        myButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        addElements()
    }


}

我不确定为什么这行不通或我错过了什么。

3 个答案:

答案 0 :(得分:2)

这不起作用,因为您要在此处创建全新的VC:

{
  "name": "something",
  "version": "1.0.0",
  "description": "something",
  "main": "index.js",
  "scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js",
    "test": "NODE_ENV=test jest --watch"
  },
  "author": "Handmadenesia",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.388.0",
    "axios": "^0.18.0",
    "babel-core": "^6.26.3",
    "babel-plugin-styled-components": "^1.10.0",
    "dotenv-webpack": "^1.7.0",
    "express": "^4.16.4",
    "isomorphic-unfetch": "^3.0.0",
    "js-cookie": "^2.2.0",
    "moment": "^2.23.0",
    "next": "^7.0.2",
    "react": "^16.7.0",
    "react-content-loader": "^3.4.2",
    "react-dom": "^16.7.0",
    "react-helmet": "^5.2.0",
    "styled-components": "^4.1.3"
 },
 "babel": {
   "env": {
     "development": {
     "presets": [
        "next/babel"
     ],
    "plugins": [
      [
        "styled-components",
        {
          "ssr": true,
          "displayName": true
        }
      ]
    ]
  },
  "production": {
    "presets": [
      "next/babel"
    ],
    "plugins": [
      [
        "styled-components",
        {
          "ssr": true,
          "displayName": true
        }
      ]
    ]
  }
}

您的自定义// Change the background color for the ViewController let vc = ViewController() // This VC is not the same one as the one that's presented on screen vc.view.backgroundColor = .red 不知道,并且不应该了解控制它的视图控制器。 VC应该处理这个。

您的UIButton子类应该是:

UIButton

您应该在VC中将VC添加为按钮的目标。

我的意思是:

class CustomButton: UIButton{
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.translatesAutoresizingMaskIntoConstraints = false
        self.backgroundColor = .blue
        self.setTitleColor(.white, for: .normal)
        self.setTitle("Press Me", for: .normal)
        self.layer.cornerRadius = 15

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

答案 1 :(得分:0)

如果要更改UIViewController的背景颜色,则必须通过该控制器。

请按照以下步骤操作:-

第一步-创建自定义按钮类并创建viewController的{​​{1}}变量类型,以便您可以分配特定的控制器来更改UIViewController颜色的背景。 / strong>

UIViewController

第二步-UIViewController代码

import UIKit

class CustomButton: UIButton {

    var viewController: UIViewController?

    override func awakeFromNib() {
        super.awakeFromNib()

        self.addTarget(self, action: #selector(buttonPressed(sender:)), for: .touchUpInside)
    }

    @objc func buttonPressed(sender: UIButton) {
        viewController?.view.backgroundColor = UIColor.red
    }

}

答案 2 :(得分:0)

  • 发生这种情况是因为您的 ViewController实例已更改。您正在尝试通过在 buttonPressed()方法中为其创建新的实例来更改ViewController的背景颜色。这样,您的ViewController的当前实例和这个新创建的实例是不同的,因此背景颜色不会更改。
  • 您可以通过在 ViewController 类中添加 Notification 并在按钮操作中发布 Notification 来做到这一点即 buttonPressed()
  • 请按照以下步骤操作:
  • 将此代码添加到ViewController的 viewDidLoad()

NotificationCenter.default.addObserver(self, selector: #selector(changeBackgroundColor), name: NSNotification.Name(rawValue: “load”), object: nil)

  • ViewController.swift 文件中添加以下功能:

为-

func changeBackgroundColor() {
self.view.backgroundColor = UIColor.purple 
}
  • 现在在 buttonPressed()中以-NotificationCenter.default.post(name: Notification.Name(rawValue: "load"), object:nil)
  • 的形式发布上述通知。