提供的鏈接對iOS7有很好的答案,但是使用Objective C/Swift,特別是當再次按下當前選定的段時取消選擇段。
這裏是需要使用TouchesEnded事件而不是TouchesBegan的C#版本。使用TouchesBegan爲我引發了兩次UISegmentedControl.ValueChanged事件,這導致了不正確的行爲。
此代碼包括處理段被觸摸並拖動控件取消事件。
class OptionalSegmentedControl : UISegmentedControl
{
public override void TouchesEnded(NSSet touches, UIEvent evt)
{
// Getting touch information to work out whether segment has been pressed, then dragged off to cancel the event
// Comment these lines out if you don't care about handling this
CGPoint locationPoint = ((UITouch)touches.AnyObject).LocationInView(this);
CGPoint viewPoint = this.ConvertPointFromView(locationPoint, this);
// Save the selected segment first
nint current = this.SelectedSegment;
// then fire the event
base.TouchesEnded(touches, evt);
// Check if the touch point is still on the control when the touch has ended,
// as well as comparing the current and new selected segment values
// and then fire the ValueChanged event if the same segment is pressed
// Use this line and comment the second if statement if you don't care about handling click and drag to cancel the event
//if (current == this.SelectedSegment)
if ((this.PointInside(viewPoint, evt)) && (current == this.SelectedSegment))
{
this.SelectedSegment = -1;
SendActionForControlEvents(UIControlEvent.ValueChanged);
}
}
}
然後在ValueChanged事件,你做你需要做的UISegmentedControl什麼:
// cell.SegmentedControl for me was a UISegmented control in a UITableViewCell
cell.SegmentedControl.ValueChanged += (s, e) =>
{
OptionalSegmentedControl osc = (OptionalSegmentedControl)s;
// continue with your code logic.....
};
有一點要注意的是,我開始用的touchesBegan無效,但後來更名爲當我意識到這是iOS7及更高版本所需要的東西時觸摸已結束。仍然沒有工作,直到我意識到我必須也改變了線路:
base.TouchesEnded(touches, evt);
所以不要忘記改變,如果你的距離的touchesBegan轉換爲TouchesEnded。
感謝poupou。對不起,我花了這麼長時間才把這個標記爲答案,我不願意做不同的事情。你的迴應非常有幫助! – Symmetry
注意自我...「問題鏈接的最後一個答案」是模棱兩可的,是一個移動的目標。最好提供一個答案的鏈接,而不是問題。 –