在视图控制器 (Swift) 中为 UIButton Class 设置布尔值

Set bool for UIButton Class in View controller (Swift)

我的 UIButton 有一个自定义 Class。在这个 class 中,我有下面的代码来绘制按钮。我希望用户点击一个按钮并切换隐藏/不隐藏的一部分。我不知道如何为此设置 Bool 值。谢谢

import UIKit

class CheckboxChecked: UIButton {

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

func drawTicked(#showTick: Bool) {

    //// Rectangle Drawing
    let rectanglePath = UIBezierPath(roundedRect: CGRectMake(3, 3, 34, 34), cornerRadius: 10)
    UIColor.darkGrayColor().setStroke()
    rectanglePath.lineWidth = 3
    rectanglePath.stroke()


    if (showTick) {
        //// Bezier Drawing
        var bezierPath = UIBezierPath()
        bezierPath.moveToPoint(CGPointMake(9.5, 19.5))
        bezierPath.addLineToPoint(CGPointMake(18.5, 26.5))
        bezierPath.addLineToPoint(CGPointMake(30.5, 10.5))
        bezierPath.lineCapStyle = kCGLineCapRound;

        bezierPath.lineJoinStyle = kCGLineJoinRound;

        UIColor.darkGrayColor().setStroke()
        bezierPath.lineWidth = 3
        bezierPath.stroke()
    }
}


override func drawRect(rect: CGRect) {
    // Drawing code
}


}

我建议您使用内部 UIButton 组件以及您想要隐藏的任何其他组件来创建一个新的 UIView

然后您可以将点击处理程序添加到控件的 UIButton 部分,然后控制其他组件的 .visible 状态。事实上,您可能可以在 Playground 中对此进行模拟。

如果你真的想变得很花哨,你可以看看 @IBInspectible 在自定义组件上查看这个 post:https://www.weheartswift.com/make-awesome-ui-components-ios-8-using-swift-xcode-6/

我使用下面的代码设法实现了这一点。

我有一个 UIButton class:

 override func drawRect(rect: CGRect) {
    // Drawing code

    //// Rectangle Drawing
    let rectanglePath = UIBezierPath(roundedRect: CGRectMake(3, 3, 34, 34), cornerRadius: 10)
    UIColor.darkGrayColor().setStroke()
    rectanglePath.lineWidth = 3
    rectanglePath.stroke()


    if (darwCheck == true) {
        //// Bezier Drawing
        var bezierPath = UIBezierPath()
        bezierPath.moveToPoint(CGPointMake(9.5, 19.5))
        bezierPath.addLineToPoint(CGPointMake(18.5, 26.5))
        bezierPath.addLineToPoint(CGPointMake(30.5, 10.5))
        bezierPath.lineCapStyle = kCGLineCapRound;

        bezierPath.lineJoinStyle = kCGLineJoinRound;

        UIColor.darkGrayColor().setStroke()
        bezierPath.lineWidth = 3
        bezierPath.stroke()
    }
}

ViewController 中,我有一个更改全局布尔变量并重新绘制按钮的按钮。

drawCheck = true
checkboxButton.setNeedsDisplay()