gpt4 book ai didi

ios - 如何向 subview 属性 Swift 添加操作?

转载 作者:行者123 更新时间:2023-11-30 13:46:48 24 4
gpt4 key购买 nike

我对 Swift 比较陌生,我想向我的自定义添加一系列操作 UIView按钮

这是代码,但是当我按下按钮时,我会收到此错误。

请告诉我对此进行建模的最佳实践。

class CameraView: UIView {

var cameraButton : UIButton?

convenience init() {
self.init(frame: CGRectZero)
self.backgroundColor = UIColor.clearColor()

cameraButton = UIButton()

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

override init(frame: CGRect) {
super.init(frame: frame)
}


func setButton(button : UIButton){
self.cameraButton = button
}


func setUpMyView(){
self.cameraButton = UIButton()
self.cameraButton?.layer.cornerRadius = 30
self.cameraButton?.layer.borderWidth = 5
self.cameraButton?.backgroundColor = UIColor.clearColor()
self.cameraButton?.layer.borderColor = UIColor.whiteColor().CGColor

self.addSubview(cameraButton!)
}

}


ViewController.swift


import UIKit

class ViewController: UIViewController {

var cameraView : CameraView?

override func viewDidLoad() {
super.viewDidLoad()

cameraView = CameraView()

cameraView?.cameraButton?.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)

self.view = cameraView

}

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


func pressed(sender : AnyObject!){
print("Button Pressed")
let alert = UIAlertController(title: "Alert", message: "Another Alert", preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)

self.presentViewController(alert, animated: true , completion: nil)
}

}

错误

2016-01-16 14:00:42.023 TPProject[4194:1442964] -[TPProject.ViewController pressed]: unrecognized selector sent to instance 0x125655a302016-01-16 14:00:42.028 TPProject[4194:1442964] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TPProject.ViewController pressed]: unrecognized selector sent to instance 0x125655a30'*** First throw call stack:(0x183d39900 0x1833a7f80 0x183d4061c 0x183d3d5b8 0x183c4168c 0x188a63e50 0x188a63dcc 0x188a4ba88 0x188a636e4 0x188a63314 0x188a5be30 0x188a2c4cc 0x188a2a794 0x183cf0efc 0x183cf0990 0x183cee690 0x183c1d680 0x18512c088 0x188a94d90 0x1000adf64 0x1837be8b8)libc++abi.dylib: terminating with uncaught exception of type NSException

最佳答案

我找到了解决办法。我必须在操作中添加 :

从这条线

cameraView?.cameraButton?.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)

cameraView?.cameraButton?.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)

关于ios - 如何向 subview 属性 Swift 添加操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com