سؤال

في طريقة viewDidLoad على UIViewController، وأفعل هذا:

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];                       // EDIT: should be 'b'
NSLog(@"button title: %@", [b titleLabel].text);

ويعرض زر ولكن العنوان لا. وNSLog يطبع خط "اختبار" إلى وحدة التحكم. أي اقتراحات بشأن ما أفعله خطأ؟

هل كانت مفيدة؟

المحلول

لا استطيع ان اقول لكم لماذا لا يعمل، ولكن لدي حل:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;        
b. frame = CGRectMake(0, 0, 100, 100);

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self addSubview:b];   

ومستقلة جاهزة خلق الإطار من تخصيص والحرف الأول من زر.

نصائح أخرى

والمشكلة تكمن مع

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

وbuttonWithType بإرجاع كائن تهيئة autoreleased. لا يمكنك إرسالها إلى initWithFrame مرة أخرى كما يمكن تهيئة كائن مرة واحدة فقط.

وتعيين إطاره حدة:

b.frame = CGRectMake(0, 0, 100, 100);

هل هذا بدلا من ذلك:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 100);
[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];  

والشيء هو أن يكون لديك للذهاب ل[[UIButton alloc] initWithFrame:] أو [UIButton buttonWithType:]، يجب عدم استخدام كليهما معا.

ويمكنك القيام بما يلي:

UIButton *b=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];

وb=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[b setTitle:@"Button Title Here" forState:UIControlStateNormal];
[b setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];

وكان لي نفس المشكلة وانتهى به الأمر إلى حقيقة أن كنت وضع صورة بدلا من backgroundImage. كل شيء عملت غرامة عندما فعلت:

[button setBackgroundImage:image forState:UIControlStateNormal];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top