我在使用 UIButton 和 UIView 时遇到的两个问题
我在 iPhone 上编程的时间并不长,但我通过谷歌搜索遇到的问题慢慢地学会了它。不幸的是我无法找到这些问题的答案。
我在 Xcode 3.2.2 中启动了一个新的基于视图的应用程序,并立即添加了以下文件:myUIView.m 和 myUIView.h,它们是 UIView 的子类。在 Interface Builder 中,我将默认 UIView 的子类设置为 myUIView。
我在drawRect方法中做了一个按钮。
问题一:按钮的标题仅在我单击屏幕后出现,为什么?
问题二:我希望按钮生成模态视图 - 这可能吗?
代码如下:
#import "myUIView.h"
@implementation myUIView
- (void)drawRect:(CGRect)rect {
// Drawing code
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0,0,100,100);
[button setTitle:@"butty" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
-(void)buttonPressed:(id)sender{
NSLog(@"Button pressed");
//present modal view somehow..?
}
我看不到如何发布附件,但如果有人认为这会有所帮助,我可以上传源代码。
非常感谢, 安迪
I haven't been programming on the iPhone for very long, but I'm picking it up slowly by googling problems I get. Unfortunately I haven't been able to find an answer for these.
I have started a new View-based application in Xcode 3.2.2 and immediately added the following files: myUIView.m and myUIView.h, which are subclasses of UIView. In Interface Builder, I set the subclass of the default UIView to be myUIView.
I made a button in the drawRect method.
Problem one: The title of the button only appears AFTER I click the screen, why?
Problem two: I want the button to produce the modalview - is this possible?
The code is as follow:
#import "myUIView.h"
@implementation myUIView
- (void)drawRect:(CGRect)rect {
// Drawing code
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(0,0,100,100);
[button setTitle:@"butty" forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
}
-(void)buttonPressed:(id)sender{
NSLog(@"Button pressed");
//present modal view somehow..?
}
I can't see how to post attachments, but if anyone thinks it will help I can upload the source.
Many thanks,
Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
drawRect
:用于自定义绘图。您并不经常需要这样做。在发送drawRect
: 之前,您的按钮不会被绘制,可能是在运行循环的下一次迭代中(即,当您单击视图时)。如果您想要在视图上有一个按钮,请使用 IB 将其拖动到那里,或者将代码从
drawRect:
移动到viewDidLoad
。您可以通过以下方式从视图控制器呈现模态视图:
在按钮发送到视图控制器的操作方法中执行此操作。这应该表明您需要查看您的应用程序设计。
drawRect
: is for custom drawing. You won't often need to do that. Your button won't be drawn until it gets sentdrawRect
:, probably in the next iteration of the run loop (ie, when you click on the view).If you want a button on your view, either drag it there using IB, or move the code from
drawRect:
toviewDidLoad
.You present a modal view from a view controller by:
Do this in the action method your button sends to your view controller. This should indicate to you that you need to take a look at your application design.