2016-08-12 49 views
3

我放置一個NSSearchField並將其邊框設置爲none,我發現清除按鈕不可點擊a.k.a.點擊時沒有響應。如果我再次設置邊框,它工作正常。OSX可可NSSearchField清除按鈕沒有響應點擊

enter image description here

我已經調試這幾個小時,並發現,當我邊框設置爲無,文本編輯器的寬度將擴大和陰影(蓋)清除按鈕。

截圖

enter image description here

查看層次調試截圖

enter image description here

重現步驟:

  1. 創建一個空的可可項目/應用
  2. 放置一個NSSearchField
  3. 設置邊框無
  4. 運行應用程序,填補了搜索領域,並嘗試點擊清除按鈕

這是一個錯誤?或者它是否打算這樣做?

注:新手可可開發

回答

7

我面對這個問題,並認爲它是可可的錯誤。但是在自定義控件或視圖控制器中很容易修復。只要保持界面構建器中的文本字段的邊界,然後通過擁有新的CALayer來殺死邊界。例如:

class ViewController: NSViewController { 


@IBOutlet weak var searchField: NSSearchField! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let maskLayer = CALayer() 
    searchField.layer = maskLayer 
    maskLayer.backgroundColor = searchField.backgroundColor?.CGColor 
} 
} 

正如你所看到的,我只是在新層中恢復控制顏色而不保留其他任何東西。這並不完美,但至少可以帶來好的開始。

+0

謝謝,這個伎倆! –

0

在代碼中創建的NSSearchField中有相同的問題。通過在子類中重寫NSSearchFieldCell方法解決它:

- (void)selectWithFrame:(NSRect)aRect inView:(NSView *)controlView editor:(NSText *)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength 
{ 
    NSRect newRect = aRect; 
    newRect.size.width -= (NSWidth([self searchButtonRectForBounds:aRect]) + NSWidth([self cancelButtonRectForBounds:aRect])); 
    [super selectWithFrame:newRect inView:controlView editor:textObj delegate:anObject start:selStart length:selLength]; 
} 

這種方法是在球場上的文本區域中鼠標點擊後調用。它似乎也是設置插入點顏色的好地方。

+0

此解決方案的問題是,如果Apple修復了selectWithFrame中的錯誤,那麼您將傳遞比您應該做的更小的矩形,並且搜索字段太小。 Eugene的解決方案是插入一個隱藏邊界的圖層,當bug修復時不太可能產生任何負面影響。 – tarmes

0

julia_v's answer幾乎是正確的。您還應該從rect.origin.x中刪除searchButtonWidth以將回調抵消掉。

而且我還增加了一些邏輯,只在需要時才製作這些「技巧」。

override func select(withFrame rect: NSRect, in controlView: NSView, editor textObj: NSText, delegate: Any?, start selStart: Int, length selLength: Int) { 

    var newRect = rect 

    if !isBordered || isBezeled { 
     let cancelButtonWidth = NSWidth(cancelButtonRect(forBounds: rect)) 
     let searchButtonWidth = NSWidth(searchButtonRect(forBounds: rect)) 

     newRect.size.width -= (cancelButtonWidth + searchButtonWidth) 
     newRect.origin.x += searchButtonWidth 
    } 
    super.select(withFrame: newRect, in: controlView, editor: textObj, delegate: delegate, start: selStart, length: selLength) 
} 

創建子後只需將其設置爲在IB身份檢查NSSearchFieldCell實例。