我正在处理一个我不明白的XCode错误,我现在一直在寻找解决方案,而且Pods更新,XCode重启或其他任何事情似乎都没有抛弃问题...
我有一个从UIButton扩展的自定义类:
import Foundation
import UIKit
//@IBDesignable <-- COMMENTED BUT SAME ERRORS ...
class CustomCardButton: UIButton {
var nibName = "CustomCardButton"
@IBOutlet weak var btnImageView: UIImageView!
@IBOutlet weak var btnLabel: UILabel!
@IBInspectable var image: UIImage? {
get {
return btnImageView.image
} set(image) {
btnImageView.image = image
}
}
@IBInspectable var label: String? {
get {
return btnLabel.text
} set(label) {
btnLabel.text = label
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
let view = loadViewFromNib()
view.frame = self.bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
btnImageView.layer.cornerRadius = 60/2
btnImageView.layer.borderColor = UIColor(red: 5/255,
green: 66/255, blue: 38/255, alpha: 1).CGColor
btnImageView.layer.borderWidth = 2
btnLabel.font = UIFont.boldSystemFontOfSize(14.0)
btnImageView.userInteractionEnabled = true
btnLabel.userInteractionEnabled = true
view.userInteractionEnabled = true
addSubview(view)
}
func loadViewFromNib() -> UIButton {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton
return view
}
}
来自SO的正确复制粘贴代码:Swift, Custom UIButton does not work when click
我的xib文件如下所示:
我现在保持简单,昨天我尝试了一个更复杂的(是的2个标签和一个imageview Woooh,复杂的xcode ......)我也有同样的错误..
错误是:
预编译:
应用程序启动后崩溃,我有这个:
30 let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton
主题1:EXC_BAD ACCESS(代码= 2,地址= 0x16fc5bfd0)
31 let view = loadViewFromNib()
主题1:EXC_BAD ACCESS(代码= 2,地址= 0x16fc5bfd0)
32 setup()
主题1:EXC_BAD ACCESS(代码= 2,地址= 0x16fc5bfd0)
我从31到2840得到了这些错误......
我看到它是一个XCode错误,我们无法做任何事情,但我真的需要一个带有2个标签和ImageVIew的自定义按钮......
答案 0 :(得分:1)
您需要UIView's
课程只是UIView
而不是您的自定义课程,在这种情况下,您的自定义课程是File's owner
。
您在加载时实例化该视图,因此如果自定义类将是您的类,它将反复运行...
笔尖:
使用UIView
制作UIButton
作为子视图(如果您的视图是某些UIView,您将其更改为UIButton
,则IBActions
将无效,最好使用UIButton
作为子视图
现在您可以将IBOutlets
拖动到File's owner
,只需按住File's owner
拖动到所需的视图:
您可以使用IBActions
按钮
您的代码会稍微改变一下:
所说的自定义类是 UIView
:
@IBDesignable class CustomCardButton: UIView
loadViewFromNib
方法将返回UIView
,而不是UIButton
:
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
那就是它,你应该在你的故事板上看到你的IBDesignable
:
使用IBInspectables
: