Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

iphone - UIImageView as button

I'm trying to make a UIImageView accept actions and fire them everytime it clicked on the UIImageVie, but i'm having hard time in getting it to work, please help me out

but here is what i'm doing:

[View setUserInteractionEnabled:YES];

[View addTarget:self action:@selector(myAction:) forControlEvents:UIControlEventTouchUpInside];


- (void) myAction:(id)sender
{
    NSLog(@"It works!");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Objective-C

In your viewDidLoad: method write this:

-(void)viewDidLoad {

    UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(100.0, 100.0, 100.0, 100.0)];
    [imageview setImage:[UIImage imageNamed:@"image.png"]];
    [imageview setUserInteractionEnabled:YES];

    UITapGestureRecognizer *singleTap =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapping:)];
    [singleTap setNumberOfTapsRequired:1];
    [imageview addGestureRecognizer:singleTap];

    [self.view addSubview:imageview];
}

Then call your gesture method like this:

-(void)singleTapping:(UIGestureRecognizer *)recognizer {
    NSLog(@"image clicked");
}

Swift

override func viewDidLoad() {
    super.viewDidLoad()

    let imageView: UIImageView = UIImageView(frame: CGRect(x: 100.0, y: 100.0, width: 100.0, height: 100.0))
    imageView.image = UIImage(named: "image.png")
    imageView.isUserInteractionEnabled = true

    let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.singleTapping(recognizer:)))
    singleTap.numberOfTapsRequired = 1
    imageView.addGestureRecognizer(singleTap)

    self.view.addSubview(imageView)
}

@objc func singleTapping(recognizer: UIGestureRecognizer) {
    print("image clicked")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...