【问题标题】:UIButton in PaintCode (Swift)PaintCode 中的 UIButton (Swift)
【发布时间】:2016-07-19 11:07:20
【问题描述】:

所以我一直在 Xcode 中使用 PaintCode 和 StyleKits。我做了一个按钮,用它自己的子类创建了一个 UIView,它在我的 ViewController 和我的设备上显示得很好。但是,我想将此 UIView 转换为 UIButton,因为我希望代码在被点击时执行。我该怎么做呢?

谢谢大家,祝你们玩得开心:)

【问题讨论】:

    标签: ios swift uiview uibutton paintcode


    【解决方案1】:

    我使用 PaintCode 的 UIImage 方法,并将该 UIImage 用作 UIButton 的图像。这是我使用的代码,它在 ObjC 中,但应该很容易转换为 Swift。

    PaintCode 生成的代码——你不需要写的东西(假装这个类叫做 PaintCodeClass):

    + (UIImage*)imageOfIcon
    {
       if (_imageOfIcon)
            return _imageOfIcon;
    
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(30, 30), NO, 0.0f);
        [PaintCodeClass drawIcon];
    
        _imageOfIcon = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return _imageOfIcon;
    }
    

    和我的代码:

    UIImage *image = [PaintCodeClass imageOfIcon];
    UIButton *button = (initialize, set frame, etc)
    [button setImage:image forState:UIControlStateNormal];
    

    有些人更喜欢这样:

    [button setBackgroundImage:image forState:UIControlStateNormal];
    

    如果你真的想要,你可以这样做:

    [button addSubview:whateverThePaintCodeViewIsCalled];
    

    但这不会像一个按钮 - 所以你可能不想这样做。

    【讨论】:

    • 非常感谢您的回复。我最初在 UIView 上使用了 TapGestureRecognizer,然后创建了一个到另一个 VC 的 segue,但后来我找到了一个更优雅的解决方案。我为 UIButton 创建了一个新的子类,并使用了相同的 StyleKit 绘图方法。然后,我在界面生成器中拖动一个按钮并将类更改为我定义的子类。像魔术一样工作。
    【解决方案2】:

    @Mitch Cohens 在 Swift 4.1 中的回答:

    static var icon: UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize.init(width: 50, height: 50), false, 0.0)
        PaintCodeClass.drawIcon()
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    

    用法:

    button.setImage(PaintCodeClass.icon, for: .normal)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2018-10-08
      • 1970-01-01
      相关资源
      最近更新 更多