开发者

I'm implementing a UIView subclass with drawRect: how can I draw a button?

开发者 https://www.devze.com 2023-03-08 02:30 出处:网络
I have a UIView subclass that I am making for a commonly used small view throughout my application. I draw the images and text of the view no problem 开发者_如何学运维and now I must add 2 buttons to t

I have a UIView subclass that I am making for a commonly used small view throughout my application. I draw the images and text of the view no problem 开发者_如何学运维and now I must add 2 buttons to this view. What is the correct way to do this?


Any view can have subviews, even if the view implements drawRect:. The content of a subview always overlays the content of the superview. And a UIButton is a view. So just add your buttons as subviews of your custom view.


You can simply add it like this:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[button setTitle:@"Button title" forState:UIControlStateNormal]; //Set the title for regular state
[button addTarget:self 
       action:@selector(yourMethod:)
 forControlEvents:UIControlEventTouchDown];
button.frame = CGRectMake(40, 100, 160, 240); //make the frame
[view addSubview:button]; //add to current view

There already are a couple of threads covering this topic though, use the search bar. :)


//required ...
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"who am i?" forState:UIControlStateNormal];
[button setFrame:CGRectMake(20, 20, 200, 40)];
[button addTarget:self action:@selector(performAction) forControlEvents:UIControlEventTouchUpInside];

//optional properties..
[button setBackgroundColor:[UIColor greenColor]];
[button setImage:[UIImage imageNamed:@"someImg.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"green-hdr-bg.png"] forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];

[yourCustomView addSubview:button];



-(void)performAction
{
    //do you button click task here
}
0

精彩评论

暂无评论...
验证码 换一张
取 消