2011-02-11 15 views
15

असल में मैं अपने सेक्शन हेडर का फ़ॉन्ट और रंग बदलना चाहता हूं, इसलिए मैं tableVieW:viewForHeaderInSection लागू करता हूं। सबसे पहले मैं इस कोड की कोशिश की:tableVieW क्यों है: viewForHeaderInSection मेरे UILabel की फ्रेम प्रॉपर्टी को अनदेखा करता है?

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UILabel* headerLabel = [[[UILabel alloc] init] autorelease]; 
    headerLabel.frame = CGRectMake(10, 0, 300, 40); 
    headerLabel.backgroundColor = [UIColor clearColor]; 
    headerLabel.textColor = [UIColor blackColor]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:18]; 
    headerLabel.text = @"My section header"; 

    return headerLabel; 
} 

लेकिन किसी कारण फ्रेम संपत्ति नजरअंदाज कर दिया है के लिए (मैं बाईं तरफ 10px इनसेट के बारे में बात कर रहा हूँ)। अब मैं निम्नलिखित का उपयोग करता हूं:

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { 
    UIView* headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)] autorelease]; 

    UILabel* headerLabel = [[UILabel alloc] init]; 
    headerLabel.frame = CGRectMake(10, 0, 300, 40); 
    headerLabel.backgroundColor = [UIColor clearColor]; 
    headerLabel.textColor = [UIColor blackColor]; 
    headerLabel.font = [UIFont boldSystemFontOfSize:18]; 
    headerLabel.text = @"My section header"; 

    [headerView addSubview:headerLabel]; 
    [headerLabel release]; 

    return headerView; 
} 

वांछित परिणाम के साथ। क्या कोई मुझे समझा सकता है कि दूसरा दृष्टिकोण क्यों काम करता है और पहला नहीं करता है?

पी एस। दोनों ही मामलों में मैं tableView:heightForHeaderInSection रूप में अच्छी तरह लागू, लौटने 40.0

उत्तर

25

ऐसा इसलिए है क्योंकि UITableView स्वचालित रूप से आप

(0, y, table view width, header view height)

y को प्रदान करते हैं हैडर देखने के फ्रेम सेट है दृश्य और header view height की गणना स्थिति है मूल्य tableView:heightForHeaderInSection:

+0

फिर मुझे इस कोड को प्राप्त करने के लिए वास्तव में मेरे कोड में "हेडर व्यू" की आवश्यकता है, है ना? – phi

+0

हां, आपको इसकी आवश्यकता है :) – Jilouc

+0

ग्रेट, धन्यवाद :) – phi

0

हो सकता है कि यह बेहतर है के द्वारा दिया जाता है एक subview जोड़ सकता हूँ:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) 
    let label = UILabel(frame: CGRect(x: 15, y: 5, width: tableView.frame.width, height: 20)) 
    label.text = "\(sections[section].year)" 
    view.addSubview(label) 
    return view 
} 
संबंधित मुद्दे