Keywords: UIButton, titleLabel, imageView, frame, bounds, size, width
如果你讀過 [iOS]調(diào)整UIButton的title和image詳解 - 簡(jiǎn)書 與 stackOverFlow 上的這篇 坛芽,會(huì)發(fā)現(xiàn)獲取一個(gè) size 屬性是個(gè)多大的坑……因?yàn)樽?iOS8 起留储,一個(gè) UIButton 內(nèi)部的 titleLabel / imageView 的 frame / bounds 只有等這個(gè)按鈕完成了自己的初始化后才會(huì)生成(據(jù)我推測(cè)~)。
因此咙轩,iOSers 發(fā)明了許多詭異的獲取 size 的方法获讳。比如提前[self setNeedsLayout]; [self layoutIfNeeded];
,或者提前調(diào)用一下 titleLabel / imageView 的屬性活喊,或者將獲取 size 放入 dispatch_async(dispatch_get_main_queue()...
中丐膝。這些我統(tǒng)統(tǒng)試過,然而都不好用钾菊。
那怎么獲取呢帅矗?答案是:[titleLable.text sizeWithAttributes: userAttributes].width
。
PS: 已經(jīng)加載按鈕后煞烫,要根據(jù)文字變化浑此,動(dòng)態(tài)改變按鈕的 frame 要重新加載按鈕……很麻煩。
篇二:控件如何綁定類方法滞详?
keywords: class method, UIButton, 按鈕, addTarget, action
[xxxTextField addTarget:[SomeClass class]
action:@selector(method)
forControlEvents:UIControlEventXxx];
篇三:如何在 UITextField 的委托方法中重設(shè)一個(gè)復(fù)雜的占位符(placeholder)
按:需求合理而實(shí)現(xiàn)詭異的情況總是層出不窮……
Q1: 什么樣的合理需求凛俱?
A1: 用戶點(diǎn)擊輸入框,占位符消失料饥。若 TA 離開時(shí)沒有輸入任何文本蒲犬,則占位符得重新變回來(lái)。
Q2: 什么叫復(fù)雜的占位符岸啡?
A2: 包括但不限于:與「輸入時(shí)」(Editing Time?) 不同的對(duì)齊方式原叮,由 NSAttributedString 創(chuàng)建,同時(shí)根據(jù)不同機(jī)型還做了字號(hào)縮放之類的適配……
栗子(兼解決方案):
- (void)setMonthTextFieldPlaceholder:(UITextField *)tf {
if ((is4S || is5S) && (isEN || isTh)) {// Thailand
tf.textAlignment = NSTextAlignmentCenter;
tf.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:NSLocalizedString(@"card_month", nil)
attributes:@{
NSFontAttributeName : [UIFont systemFontOfSize:contentFontSize - 1]
}
];
} else {
tf.placeholder = NSLocalizedString(@"card_month", nil);
tf.textAlignment = NSTextAlignmentRight;
}
解釋:在 View 中創(chuàng)建 textField 時(shí)巡蘸,就把設(shè)置占位符的部分單獨(dú)用一個(gè)函數(shù)來(lái)寫篇裁。(由于指針的關(guān)系,對(duì)形參的操作可直接影響實(shí)參~)再把這個(gè)設(shè)置方法暴露在頭文件里赡若。
使用:比如在委托方法- (void)textFieldDidEndEditing:(UITextField *)textField
你就可以通過:
if (!textField.text.length) {
[someView setMonthTextFieldPlaceholder:textField];
}
來(lái)輕松重設(shè)一個(gè)「復(fù)雜的」占位符了~
PS: 實(shí)際的需求其實(shí)更麻煩达布,某些語(yǔ)言占位符要居右,而開始輸入時(shí)要居中逾冬。然而只要占位符在黍聂,那么光標(biāo)要么居左要么居右躺苦,設(shè)置居中是不行的,所以要提前把 palceholder = nil产还。
如果之后用戶沒輸入匹厘,再調(diào)用 setPlaceholder 方法……
PS2: shouldChangeCharactersInRange:(NSRange)range 是有坑的,原理我也不清楚脐区。具體情況是:從空 textField 輸入時(shí)的 range.location 與 編輯一個(gè)已有內(nèi)容的 textField(比如從父界面?zhèn)骰亓艘恍?shù)據(jù))時(shí)的 range.location 差了一位(內(nèi)容統(tǒng)一長(zhǎng)度的話)愈诚。有的 location 起始是這樣的:nil, 2, 3,有的是 nil, 1, 2...