LoginSignup
1
1

More than 3 years have passed since last update.

隱藏 UITextField 的 Caret

Posted at

Caret 就是在 UITextField 和 UITextView 等 UI 元件中輸入內容時會出現的那個游標。

想要改顏色雖然可以透過這樣的方式達到:

textField.tintColor = .red

不過如果想要像 iPhone 裡面預設的通訊錄 app 中,編輯生日時不會顯示游標,但是又想要在選取的時候有顏色的話該怎麼辦?
如果是像下面這樣設定的話,連選取的時候的顏色也會跟著不見:

textField.tintColor = .clear

所以顯然不是這個方法。

UITextInput#caretRect(for:)

解法不會很難,在比較底層的 protocol 有一個方法可以改變這個游標的大小。
可以新增一個 custom UITextField ,寫像是這樣的東西,就可以讓他變不見:

import UIKit

class CustomTextField: UITextField {
    override func caretRect(for position: UITextPosition) -> CGRect {
        return .zero
    }
}

但是如果把這樣寫死似乎沒有什麼彈性。

例如,當有共用的表單 UI 元件裡面有這樣的文字輸入框的時候就無法根據情境設定我要不要顯示這個游標,顯然不是很自由好用。

加入彈性

於是就來加個新的屬性 (property) 給他,讓 UI 自己可以決定是否要顯示

  • 如果這個值是 nil 的話,就顯示預設的大小。因為是繼承的關係,因此可以透過 super 呼叫相同的方法來拿到這個值。
  • 如果不是 nil 的話,就用我們期望的值。

用這個邏輯的時做就如下:

import UIKit

class TextField: UITextField {

    var caretRect: CGRect?

    // MARK: - UITextInput

    override func caretRect(for position: UITextPosition) -> CGRect {
        if let caretRect = caretRect {
            return caretRect
        }

        return super.caretRect(for: position)
    }
}

使用

使用方式如下,
不想要他顯示的話就這樣寫:

// textField is a CustomTextField's instance
textField.caretRect = .zero

想要讓他顯示的話,就這樣做就可以了:

// textField is a CustomTextField's instance
textField.caretRect = nil

結語

因為 UITextViewUITextField 都有實作 UITextInput 的方法,
所以包含 UITextView 就也可以透過相同的方式達到這樣的效果!

以上!

參考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1