How can I detect taps on a particular part (substring) of a UILabel?

前端 未结 1 1828
刺人心
刺人心 2021-02-07 21:19

I am new to iOS development. I dont know whether this questions has been asked already or not, I tried searching for the solution on stackoverflow but didn\'t get any results.<

1条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 21:30

    You could check the location of the touch to see if it is on the word "Click". This may not be completely accurate though and may break if you change the text in your label.

    What you could do is first get the location of the click by using:

    CGPoint location = [gesture locationInView:gesture.view];
    

    This gets the location of the gesture in your view.

    Once you have this, you can either have the size of the word "Click" hard-coded or you can create an identical label to your gesture label to get the size, such as:

    UILabel *sizeLabel = //create label with same font.
    [sizeLabel setText:@"Click"];
    float width = [sizeLabel sizeThatFits:CGSizeMake(MAXFLOAT,MAXFLOAT)].width;
    

    You could also do this when creating the actual label and store this width in a static variable so that you only have to do it once and you don't have to create an extra label (ie set the text of your real label to @"Click", get the width, and then set it to the real text).

    Once you have the width, you and the location of the tap, you can check if the word "Click" was tapped by comparing:

    if (location.x < width) {
        //Put your tap code in here.
    }
    

    0 讨论(0)
提交回复
热议问题