【问题标题】:How to do Custom Switch exactly like UISwitch? [closed]如何像 UISwitch 一样做自定义开关? [关闭]
【发布时间】:2017-05-02 12:32:36
【问题描述】:

我正在尝试使自定义开关与UISwitch 完全一样。哪个可以切换,按下按钮或拖动按钮。请给我一个想法。

【问题讨论】:

标签: ios objective-c custom-controls uiswitch


【解决方案1】:

您可以使用贝塞尔路径绘制自定义开关。

子类化一个 UIView 并在 drawRect 方法中使用这个方法。

这是一个使用贝塞尔路径绘制的简单开关:

- (void)drawSwitch: (CGRect)frame thumbPos: (CGFloat)thumbPos
{
    //// Color Declarations
    UIColor* yesColor = [UIColor colorWithRed: 0.237 green: 0.811 blue: 0.624 alpha: 1];
    UIColor* noColor = [UIColor colorWithRed: 0.8 green: 0.32 blue: 0.32 alpha: 1];

    //// Variable Declarations
    UIColor* switchColor = thumbPos > 20 ? yesColor : noColor;

    //// Rectangle Drawing
    UIBezierPath* rectanglePath = [UIBezierPath bezierPathWithRoundedRect:yourRect cornerRadius: 20];
    [switchColor setFill];
    [rectanglePath fill];


    //// Oval Drawing
    UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(thumbPos, 2.5, 35, 35)];
    [UIColor.whiteColor setFill];
    [ovalPath fill];
}

thumbpos 是开关中白色圆圈的位置。您可以在滑动手势上更改此设置,并通过更改此值为开关设置动画。

开关颜色将根据拇指位置改变。

【讨论】:

    【解决方案2】:

    您可以使用与 UISwitch 相同的两个图像并在点击 UIbutton 时更改设置的图像。

    【讨论】:

    • 那我怎么拖?
    • UIButton 是 UIView 的子类,因此您可以将 UIView.animateWithDuration 与按钮一起使用。例如,您可以这样说:@IBAction func buttonPressed(sender: UIButton) { UIView.animateWithDuration(0.5, animations: { sender.alpha = 0.0 }, completion:{(finished) in sender.setImage(UIImage(named: arrItems) [intItemCounter]), forState: .Normal) UIView.animateWithDuration(0.5,animations:{ sender.alpha = 1.0 },completion:nil) }) }
    【解决方案3】:

    您可以添加按钮并为状态设置图像。 您必须为两种状态设置图像-> 1:选中状态 2:默认状态

    并在这个按钮的action方法中改变状态。

    【讨论】:

    • 是否可以将按钮与手指滑动一起移动到关闭或开启状态
    • 您必须在滑动手势方法的动作中添加滑动/点击手势并更改状态。
    • 我需要通过滑动来显示移动。在滑动手势中是不可能的
    猜你喜欢
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    相关资源
    最近更新 更多