单击时,Swift,自定义UIButton不起作用 [英] Swift, Custom UIButton does not work when click

查看:1204
本文介绍了单击时,Swift,自定义UIButton不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用xib文件创建的自定义UIButton。当我在我的视图上使用我的自定义按钮时,按下它时它不起作用。

I have a custom UIButton created with xib file. When i use my custom button on my view, it does not work when i press to it.

我的RoundBtn.swift文件:

My RoundBtn.swift file:

import UIKit

@IBDesignable class RoundBtn: UIButton {

    var nibName = "RoundBtn"

    @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
    }   
}

我的RoundBtn.xib档案:

My RoundBtn.xib file:

查看我使用自定义按钮的位置:

View where i used my custom button:

我已启用所有视图组件上的userInteractionEnabled 。当我点击我的自定义按钮时,它不起作用。我尝试通过编程方式定义单击并定义动作segue(show)。

I enabled userInteractionEnabled on all view components. When i click to my custom button, it does not work. I tried by defining on click programmatically and by defining action segue (show).

@IBAction func myCartBtnPressed(sender: AnyObject) {
    print("my cart btn pressed")
}


推荐答案

我认为这是因为您使用userInteractionEnabled向当前的UIButton添加了几个UIViews子视图,这意味着他们正在处理用户输入。

I think this is caused because you're adding a couple of UIViews subviews to your current UIButton with userInteractionEnabled, which means that they're handling the user input.

如果你这样做:

view.isUserInteractionEnabled = false

RoundBtn本身将获得所有触摸事件,而不是您拥有的UIViews。

The RoundBtn itself will get all the touch events, instead of this UIViews that you have on top.

这篇关于单击时,Swift,自定义UIButton不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆