Making a custom Button using a UIView or overriding UIButton?

前端 未结 3 1468
天涯浪人
天涯浪人 2020-12-10 16:35

I need to generate a custom button through code, this is how i am currently doing it.

-(void) initialiseButtons 
{
    int ypos = playerImage.frame.origin.y          


        
3条回答
  •  遥遥无期
    2020-12-10 17:07

    You should not (I'd almost say you can't) subclass UIButton, as it turns out to be a class cluster, and it would be impractical (read: impossible) to derive from that.

    So your two options are:

    1) Use standard UIButton of custom type, add the elements you want to show (i.e. UILabel) and hook up actions for touch down and touch up and react accordingly (change the views, trigger actions etc.)

    2) Use a custom UIView, implement drawRect: to draw how you like it or use custom views as subviews as in 1). Then use the touchesBegan:, touchesEnded: etc. messages to react accordingly (or UIGestureRecognizer if you can live with 3.2+ compatibility).

    You might build a factory to build those buttons if they all are very similar, so that your code becomes clean and non-repetive.

    Edit as per iOS 6: Apple now mentions subclassing in the UIButton docs, so while still not very well defined, it seems quite safe now to do so.

提交回复
热议问题