3

我搜索了一些教程以将 UIImage 添加到单击事件的按钮。如何添加 URL 路径

图像到按钮..例如代码:

UIButton *imageView=[[UIButton alloc]initWithFrame:CGRectMake((320*index)+countFlag*80+ 2, 5, 75, 75)];
                imageView.tag=i+1;
                [imageView addTarget:self action:@selector(imageViewClicked:) forControlEvents:UIControlEventTouchUpInside];
                [imageView.layer setBorderColor:[UIColor lightGrayColor].CGColor];
                [imageView.layer setBorderWidth:1.0f];
                switch ((i+1)%5) {
                    case 0:
                        [imageView setImage:[UIImage imageNamed:@"img1.png"] forState:UIControlStateNormal];               

                        break;

                    case 1:
                        [imageView setImage:[UIImage imageNamed:@"img2.png"]  forState:UIControlStateNormal];

                        break;
    }
4

5 回答 5

3

最好使用SDWebImageUIButton+WebCache.h这一类,它支持为你的按钮异步加载图片。您可以使用以下任何一种方法。

- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state;
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;

它还提供背景图片异步加载UIButton

- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
- (void)setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;

不要忘记包含SDWebImage到您的项目中并UIButton+WebCache.h归档到您的实施文件中。

参考:https ://github.com/rs/SDWebImage

于 2013-03-21T12:20:08.553 回答
2

试试这个你的按钮(imageView)

[imageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"imageurl"]]]forState:UIControlStateNormal];
于 2013-03-21T11:56:21.553 回答
2

对于正常状态,

[imageView setImage:[UIImage imageNamed:@"img1.png"] forState:UIControlStateNormal];

对于 Clicked (Selected) 状态,

[imageView setImage:[UIImage imageNamed:@"img2.png"] forState:UIControlStateSelected];

希望这会有所帮助。

于 2013-03-21T12:07:56.577 回答
1
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"url"];
[imageView setImage:[UIImage imageWithData:data]];
于 2013-03-21T12:06:19.043 回答
0

试试这个:

    EGOImageButton* btnUserImage = [[EGOImageButton alloc] initWithPlaceholderImage:[UIImage imageNamed:@"ProfilePictureDefault.png"]];
    btnUserImage.frame = CGRectMake(10,5,25,25);
    btnUserImage.highlighted = NO;
    [self addSubview:btnUserImage];

    btnUserImage.imageURL = [NSURL URLWithString:Url];
于 2013-03-21T12:08:01.147 回答