如何向子视图属性 Swift 添加操作? [复制]
Posted
技术标签:
【中文标题】如何向子视图属性 Swift 添加操作? [复制]【英文标题】:How to add action to a subviews Attributes Swift? [duplicate] 【发布时间】:2016-01-16 14:16:30 【问题描述】:我对 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 按下]:无法识别的选择器发送到实例 0x125655a30 2016-01-16 14:00:42.028 TPProject[4194:1442964] *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[TPProject.ViewController 已按下]:无法识别的选择器发送到实例 0x125655a30” *** 首先抛出调用堆栈: (0x183d39900 0x1833a7f80 0x183d4061c 0x183d3d5b8 0x183c4168c 0x188a63e50 0x188a63dcc 0x188a4ba88 0x188a636e4 0x188a63314 0x188a5be30 0x188a2c4cc 0x188a2a794 0x183cf0efc 0x183cf0990 0x183cee690 0x183c1d680 0x18512c088 0x188a94d90 0x1000adf64 0x1837be8b8) libc++abi.dylib:以 NSException 类型的未捕获异常终止【问题讨论】:
【参考方案1】:我想出了解决办法。我必须添加一个 : 以采取行动
从这条线
cameraView?.cameraButton?.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside)
到
cameraView?.cameraButton?.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
【讨论】:
附带说明,没有必要为此子类化 UIView - 看看这里developer.apple.com/library/ios/documentation/UIKit/Reference/…。您没有覆盖任何 UIView 或 UIButton 的方法,因此您只需在 ViewController 中创建一个 UIButton 并在 ViewDidLoad() 或 LoadView() 中配置它。如果您要重用按钮的外观,您可以在 UIButtonExtension.swift 文件中为 UIButton 创建一个新方法 - 更多信息请点击此处developer.apple.com/library/ios/documentation/Swift/Conceptual/…。以上是关于如何向子视图属性 Swift 添加操作? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift 中更改 UILabel 文本某些部分的字体属性? [复制]
javascript:仅当父元素处于活动状态且子元素具有特定类时,如何向子元素添加属性?
如何在swift 4中将按钮放在表格视图控制器的前面? [复制]