【问题标题】:Put UIView on UIButton and still have it highlight将 UIView 放在 UIButton 上并仍然突出显示
【发布时间】:2012-10-12 07:43:14
【问题描述】:

过去我做过以下事情:

thumbnailButton = [[UIButton alloc] initWithFrame: thumbnailButtonFrame];
[thumbnailButton addTarget:self action:@selector(thumbnailButtonPushed:) forControlEvents:UIControlEventTouchUpInside];
[thumbnailButton setBackgroundImage: thumbnailButtonImage forState: UIControlStateNormal];
[thumbnailButtonImage release];

它创建了一个按钮,上面有一个缩略图,当按下它时,它会在上面加一个灰色突出显示(很像在照片应用程序中,当您从缩略图列表中选择要显示的照片时)。

我现在有一个场景,我有一个 UIView 类,它在它的 drawRect 方法中绘制图形。我想把这个UIView 放在UIButton 上,如果我添加图像,它会以同样的方式突出显示。我想在不继承UIButton 的情况下做到这一点。这可能吗?

【问题讨论】:

  • 你不使用2张图片并根据是否选择按钮来设置图片??

标签: iphone ios cocoa-touch uiview uibutton


【解决方案1】:

这应该可以。但是,它可能不是您正在寻找的确切方法。

它涉及转换UIView in UIImage

+ (UIImage *) imageWithView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return img;
}

然后在你的代码中调用这个方法。

[thumbnailButton setBackgroundImage:[MyClass imageWithView:myCustomView] forState: UIControlStateNormal];

这可能无法为您提供所需的性能,但它应该可以工作。

【讨论】:

    【解决方案2】:

    你可以试试这个方法。你可以有两张图片,一张是正常状态,一张是高亮状态。

    btnImage = [UIImage imageNamed:@"buttonInactiveImage.png"];
    btnImageSelected = [UIImage imageNamed:@"buttonActiveImage.png"];
    btn = [[UIButton alloc] initWithFrame: thumbnailButtonFrame];
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:btnImage forState:UIControlStateNormal]; // Set the image for the normal state of the button
    [btn setBackgroundImage:btnImageSelected forState:UIControlStateSelected]; // Set the image for the selected state of the button
    

    这样您就不必在按钮上放置任何视图

    【讨论】:

      猜你喜欢
      • 2012-02-03
      • 2014-02-19
      • 2015-06-12
      • 1970-01-01
      • 2010-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      相关资源
      最近更新 更多