简体   繁体   中英

Hit area is only on label of UIButton

I create a UIButton like this:

button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0,0,100,100);

The button works, but the hit area is only on the text, not the entire button. I've set the background of the button to be [UIColor clearColor] . What do I need to do to make it so that the entire frame of the button is the hit area?

I suppose I could change the frame of the label to equal the button, but that seems hokey. Is there a better way?

try like this,

        UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
        button.frame=CGRectMake(0,0,100,100);
        button.backgroundColor=[UIColor clearColor];
        [button setTitle:@"Set" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClicked) forControlEvents: UIControlEventTouchUpInside];
        [self.view addSubview:button];

The button in question was being built up with layers. What I ended up doing was ensuring the background layer had a solid background color. Simply setting the background of the button to clear did not work in this case.

//set a background color so it is clickable
[layer0 setBackgroundColor: CGCOLORA(0, 1) ];  

将UIButton的opaque属性设置为true对我有用(iOS10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM