ios - 仅当符合协议(protocol)时才扩展 UIButton

标签 ios swift uibutton protocols

我正在尝试为 UIButton 创建多个扩展,这样我只需向自定义按钮添加协议(protocol)即可轻松添加一些功能。如果我不必重写 UIButton 中的某些方法,那就容易多了,所以我想我必须为 UIButton 本身进行扩展。

例如,我的自定义按钮可以遵循多个协议(protocol):

protocol CustomLayer { }

protocol ButtonSound { }

到目前为止,我只设法为 UIButton 创建一个扩展,没有任何限制(这些是简化版本):

// Only when the button conforms to protocol CustomLayer
extension UIButton {
    override public class func layerClass() -> AnyClass { return CAShapeLayer.self }
}

// Only when the button conforms to protocol ButtonSound
extension UIButton {
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)

        AudioServicesPlaySystemSound(1104)
    }
}

我读过一些帖子,我可以使用 UIButton 类的 where 子句为协议(protocol)本身进行扩展:

extension CustomLayer where Self: UIButton { }

但是我无法重写 UIButton 本身的任何方法。

其他建议(例如子类化)有效,但某些按钮不能具有相同的功能:

class A: CustomLayer { } // Can't have ButtonSound, single subclass works
class B: ButtonSound { } // Can't have CustomLayer, single subclass works

class C: CustomLayer, ButtonSound { } // Error: multiple inheritance from classes

最佳答案

import Foundation

protocol BackButtonDelegate {

    func BackButtonAction(sender:UIButton)
}

class NavigationBack: UIButton
{
     var delegate : BackButtonDelegate!

    override func drawRect(rect: CGRect) {
        self.frame = CGRectMake(0, 0, 60, 60)
        self.setTitle("Back", forState: .Normal)
        self.titleLabel?.font = UIFont(name: "Helvetica",size: 12)
        self.setImage(UIImage(named: "back-arrow"), forState: .Normal)

        self.addTarget(self, action: #selector(NavigationBack.click(_:)), forControlEvents: UIControlEvents.TouchUpInside)

   }
    func click(sender:UIButton)
    {
        if delegate != nil
        {
            delegate!.BackButtonAction(sender)
        }
    }

}

关于ios - 仅当符合协议(protocol)时才扩展 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36817209/

相关文章:

ios - Xcode 中的约束变灰

ios - 应用内购买恢复

ios - UITableView 的动态高度(不是 Cell)

ios - 在 managedObjectContext 的开头插入 NSManagedObject

ios - AVCaptureVideoPreviewLayer 未填满屏幕

ios - 我如何在没有 ALAssetsLibrary 的情况下从 "UIImagePickerControllerReferenceURL"获取 UIImage

ios - UITableView 在重新加载后重置 UITableViewCell

ios - 播放声音时禁用 UIButton AVAudioplayer

ios - 使用按钮调用另一个类iOS中的方法

uinavigationcontroller - 自定义 UIBarButtonItem 与 iOS7 对齐